Tuesday, 16 September 2014

Javascript - How to check if a string contains another string

String function indexOf returns the position of the sub string in a string. If it doesn't find an occurance of the sub string, it will return -1.
var mainText = "microsoft";
var isSubstring = mainText.indexOf("soft") > -1
alert(isSubstring);
In the example, it checks for the substring "soft" within the main string "microsoft". As it find "soft" inside "microsoft", mainText.indexOf("soft") evaluates to 5 and isSubstring will be true;

No comments:

Post a Comment