tags:

views:

82

answers:

4

There is a case when I receive a string with the following special characters in it:

<!@#$%^&*()_+|}{":?></.,';][=-`~DS0>

While performing a compare operation on this string using the double equal to (==) operator in JavaScript it is not yielding the appropriate result.

Although both the strings contain the same specified string the compare operation does not return true.

My case would translate somewhat like this in JavaScript:

var strValue = "<!@#$%^&*()_+|}{":?></.,';][=-`~DS0>";
var itrValue = "<!@#$%^&*()_+|}{":?></.,';][=-`~DS0>";
if (itrValue == strValue) {
    alert("True");
} else {
    alert("false");
}
+3  A: 

It only returns true if and only if the strings are identical. You can use indexof if you want to determine if a string is inside of another one: http://www.quirksmode.org/js/strings.html#indexof

popester
+2  A: 

First: I think you need to escape those quotation marks with backslashes (something like \").

Second: as far as I can see those two strings are not identical. You might want to try something more like indexof (W3 schools reference), as popester states correctly.

KB22
actually the strings are equivalent . but somehow the editor doesnt display it appropriately. both the strings are <!@#$%^][=-~DS0>
Arun
See Boldewyn's comment.
KB22
You need to escape the '"' (and possibly any "'" as well), the stackoverflow editor actually points out your problem (look at the different colors in your code block)
laura
A: 

You can use the indexOf method which will return -1 if an index cannot be found as the two answers above state.

Something slightly different (not entirely sure if you're looking for this, indexOf is probably your best bet) is using the String.match or String.split method. String.match will return null if there is no match, otherwise it will return an array of all elements containing your string (EG:

var str = "Test123 ABC Test 123Test ABC"
var macthes = str.match("/Test/g") // You can have any regular expression here
document.write(matches[0])
document.write(matches[1])
document.write(matches[2])

Will produce Test123 Test 123Test String.split will produce an array of strings split at your initial string.

Evan
A: 

I just escaped the double quote in the string and I got a nice true from the == operator...

var strValue = "<!@#$%^&*()_+|}{\":?></.,';][=-`~DS0>";
var itrValue = "<!@#$%^&*()_+|}{\":?></.,';][=-`~DS0>";
alert(strValue == itrValue)
Victor
ya that worked victor.
Arun