AnyFormat.io - convert files and webpages to any format!
JavaScript string comparing is a very common operation for most of JS developers. Basically it's a check if one string equals another.
But there are some tricky "issues" in JavaScript when doing comparison. I will try to describe some of them and give few advices to deal with them.
Let's start with a simple code snippet in JS: var s = 'string';
if(s == 'string') {
alert(true);
} else {
alert(false);
}
Yes, it puts an alert 'true' on the screen. Pretty straightforward so far. And another example: var s = '123';
if(s == 123) {
alert(true);
} else {
alert(false);
}
This code shows 'true' too... don't you think that's strange? Comparing a number to a string gives you true. Anyway, another example: var s = '';
if(s === '123') {
alert(true);
} else {
alert(false);
}
Finally! We got 'false' alert this time, but have noted this difference in last two example? There is another interesting stuff with expressions inside the 'if' statement. For example, if you wan't to test passed parameter inside a function, you should be very careful: function testParam(param) {
if(param) {
alert(true);
} else {
alert(false);
}
}
testParam('test');//true
testParam(null);//false
testParam();//false
testParam('');//this also gives you 'false', same like if null or undefined param was passed
Good, that was simple. Comparing one string to another is always easy, but what if you need to test if some string has a substring that you're searching? alert('Hello JavaScript world!'.indexOf('world'), 5);//start search from the 6th symbol
alert('Hello JavaScript world!'.indexOf('foobar'));
This example will give you '17' and then '-1' as a result. indexOf() returns an index of char in the string where match was found. You can provide optional param to start search only from that specific position in the string. var regex = new RegExp('[0-9]+');
alert('abc433qwe234'.match(regex));//output is '433'
var regex2 = new RegExp('[0-9]+', 'ig');
alert('abc433abc123'.match(regex2));//output is an array: '433, 123'
In this example we're searching for a number as a substring in 'abc433' using the RexExp object. '[0-9]' means we're searching for digits and '+' means we wan't to all digits following the first that matched.
|
|