Possible Duplicate:
How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?
In Javascript, is it possible to find the starting and ending indices of all substrings within a string that match a regular expression?
Function signature:
function getMatches(theString, theRegex){
//return the starting and ending indices of match of theRegex inside theString
//a 2D array should be returned
}
For example:
getMatches("cats and rats", /(c|r)ats/);
should return the array [[0, 3], [9, 12]]
, which represents the starting and ending indices of "cats" and "rats" within the string.
String indexOf() Method The most common (and perhaps the fastest) way to check if a string contains a substring is to use the indexOf() method. This method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1.
The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.
The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.
Matches Method. CsharpProgrammingServer Side Programming. The method matches instances of a pattern and is used to extract value based on a pattern.
Use match
to find all substrings that match the regex.
> "cats and rats".match(/(c|r)ats/g)
> ["cats", "rats"]
Now you can use indexOf
and length
to find the start/end indices.
function getMatches(theString, theRegex){
return theString.match(theRegex).map(function(el) {
var index = theString.indexOf(el);
return [index, index + el.length - 1];
});
}
getMatches("cats and rats", /(c|r)ats/g); // need to use `g`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With