Wednesday, 13 September 2017

javascript - Check if text is in a string



I want to check is some text is in a string for instance i have a string




str = "car, bycicle, bus"


and I have another string



str2 = "car"


I want to check if str2 is in str.




I am a newbie in javascript so please bear with me :)



Regards


Answer



if(str.indexOf(str2) >= 0) {
...
}


Or if you want to go the regex route:




if(new RegExp(str2).test(str)) {
...
}


However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...