Metamerge logo
Search

Advanced Search
*
*
*
* HOME DOCUMENTS & RESOURCES DOWNLOADS EARLY TECH ACCESS SUPPORT FAQ KNOWN ISSUES OLD VERSIONS
*

 

Comparing JavaScript Strings

If you use JavaScript within your AssemblyLines, you might experience some strange behavior when comparing strings.  This is due to some not-always-intuitive behavior of  JavaScript.  

To make a long story short, you might want to append the empty string "" whenever comparing strings in JavaScript.  If you want to know why, read on.

Below is a little table that shows the behavior when comparing different variables.  All constants, string literals and JavaScript string objects below will contain the characters "test":  If the value is False, you might want to understand why. 

Test Expression Value Comments
var a = "test";
a== "test"

True
 
var a = "test";
var b = "test"
a== b


True
 
var c = new String("test");
c == "test"

True
Because the object c is casted to a string
var c = new String("test");
var d = new String("test");
c == d


False
Two string objects are created, but the objects are not the same: They merely contain strings that happens to have the same value.  Comparison is done by references.  

This is important to understand because the Entry objects all have a getString() method that returns an Object, not a string. Think of it as corresponding to doing a new String().  So assuming

var w = system.newEntry();
w.setAttribute("x","test");
w.setAttribute("y","test");
x = w.getString("y"); // really same as x = new String("test")
y = w.getString("y"); // really same as y = new String("test")

will give you 

Test Expression Value Comments
x == y FALSE Because these are two different objects, as above
x == "test" True Because x is casted to a string
var a = "test"
x == a
True As above
(x + "") == (y + "") True Because appending "" to a general Object containing a string, converts it to a JavaScript string object.
 

So unless you understand the type of the string objects you use, you might want to always play it safe by adding a "" before comparing.

Warning

The statements

n = null;
n = n + "";

will in JavaScript make the variable n contain the string "null".  So if you have two null variables, n1 and n2

Test Expression Value Comments
n1 == n2 True  
n1 + "" == n2 False Because you compare "null" and null
n1 + "" == n2 + "" True Because you compare "null" and "null"

So when forcing a 'cast' by adding "", do it on both side of the compare operand.  But you math teacher probably already told you something like this :-) 

 

 

*
  Metamerge Integrator version 4.6 ©Copyright Metamerge AS 2000-2002 Last edited 2002-06-10 contact us