13

i had string like this in javascript

var str = "This is my test string is Ingrédients";

the substring "Ingrédients" can be also as "Ingredients" how to get the index of substring "Ingrédients" from the above string by applying regular expression ( Ingr[ée]dients )

2 Answers 2

30

If you just want to find the first occurrence of a regex match in a string, you can use search. If you want to find all occurrences, then you can use repeated exec and query the match index values.

Here's an example: (see it on ideone.com):

text = "I'm cooking; these are my Ingredients! I mean Ingrédients, yes!";
//      0123456789012345678901234567890123456789012345678901234567890123

re = /Ingr[ée]dients/g;

print(text.search(re)); // "26"
print(text.search(re)); // "26" again

while (m = re.exec(text)) {
   print(m.index);
} // "26", "46"

References

Sign up to request clarification or add additional context in comments.

2 Comments

Great thanks--I don't suppose there is a built in way to just get an array of all hits back (which include index information)?
There sure is chaiguy: simply iterate a while loop and push the results onto an array. It can go on one line if you like.
-2

Use search:

alert(str.search(/Ingr[ée]dients/));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.