Comparing the following special character in JavaScript is returning inappropriate result?
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开发者_Python百科");
} else {
alert("false");
}
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
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.
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)
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.
精彩评论