I want to analize a string for a substring and return the position of the substring if it was found.
function analize(t) {
if (t.indexOf(" a ") > -1 || t.indexOf(" b ") > -1 || t.indexOf(" c ") > -1) {
alert(t.indexOf(" a "));
}
The problem is that I’m looking for more than one substring and I cant echo its position since I don’t know which was found. While this example only has 3 strings, I need to do it with a lot more in my code. How can I check for various items and return the position of the one that’s found?
Use a regular expression with String.search:
This is easy enough to code up if your list of strings is constant. But if your list is dynamic, you’d have to build the regular expression programmatically. You can do so like this:
Note that I used
Array.map()above. This will not work by default in older browsers. You have to add it in manually. See the compatibility notes for an implementation you can use to get this functionality in older browsers.