use*_*671 2 javascript regex substring
我只想找到我要搜索的子串的起点和终点位置.关于如何做到这一点的任何想法?
这是一个jsfiddle,展示了它是如何完成的......
https://jsfiddle.net/cz8vqgba/
var regex = /text/g;
var text = 'this is some text and then there is some more text';
var match;
while(match = regex.exec(text)){
console.log('start index= ' +(regex.lastIndex - match[0].length));
console.log('end index= ' + (regex.lastIndex-1));
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供字符串中所有匹配项的开始和结束索引...
根本不需要两次遍历干草堆(这可能效率较低)
你可以这样做:
"foobarfoobar".match(/bar/);
Run Code Online (Sandbox Code Playgroud)
或者:
/bar/.exec("foobarfoobar");
Run Code Online (Sandbox Code Playgroud)
都返回这个对象:
{
0: 'bar'
index: 3
input: 'foobarfoobar'
}
Run Code Online (Sandbox Code Playgroud)
所以如果你想要开始和结束位置,你只需要做如下事情:
var needle = /bar/;
var haystack = 'foobarfoobar';
var result = needle.exec(haystack);
var start = result.index;
var end = start + result[0].length - 1;
Run Code Online (Sandbox Code Playgroud)
注意这个简单的例子只给你第一个匹配;如果您期望有几场比赛,事情就会变得有点复杂。
另外,我在问题标题中回答了正则表达式,但是如果您只需要字符串匹配,您可以使用 indexOf() 进行几乎相同的操作。
| 归档时间: |
|
| 查看次数: |
3230 次 |
| 最近记录: |