Retrieve regular expression results with in-depth info
Is there a way to retrieve regular expression object that contains the start position of the match, end position, total length etc.?
Or at least something like String.search(/pattern/)
, bu开发者_开发技巧t with more than one result.
Thanks in advance!
Exec is what you're looking for I'd say.
Edit:
for example (and using the code from the linked page):
var re = /d(b+)(d)/ig;
var result = re.exec("cdbBdbsbz");
result.index
is the start positionre.lastIndex
is the end positionresult[0].length
is the total length
You could roll your own function based on exec, here is an example that builds a result object including index of all matches...
searchAll = function (text,pattern) {
var result, output = [];
while((result = pattern.exec(text)) != null) {
output.push({
result:result[0],
index:result.index,
lastIndex:pattern.lastIndex
})
}
return output
}
var s = searchAll("JavaScript is more fun than Java!",/Java/g)
alert( JSON.stringify( s ) )
精彩评论