In javascript, is there an equivalent of String.indexOf() that takes a regular expression instead of a string for the first first parameter while still allowing a second parameter ?(在javascript中,是否有一个等效的String.indexOf()为第一个第一个参数采用正则表达式而不是字符串,同时仍然允许第二个参数?)
I need to do something like(我需要做点什么)
str.indexOf(/[abc]/ , i);
and(和)
str.lastIndexOf(/[abc]/ , i);
While String.search() takes a regexp as a parameter it does not allow me to specify a second argument!(虽然String.search()将regexp作为参数,但它不允许我指定第二个参数!)
Edit:(编辑:)
This turned out to be harder than I originally thought so I wrote a small test function to test all the provided solutions... it assumes regexIndexOf and regexLastIndexOf have been added to the String object.(事实证明这比我原先想象的要难,所以我编写了一个小测试函数来测试所有提供的解决方案......它假设regexIndexOf和regexLastIndexOf已被添加到String对象中。)
function test (str) {
var i = str.length +2;
while (i--) {
if (str.indexOf('a',i) != str.regexIndexOf(/a/,i))
alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ;
if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) )
alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ;
}
}
and I am testing as follow to make sure that at least for one character regexp, the result is the same as if we used indexOf(我正在测试如下以确保至少对于一个字符regexp,结果与我们使用indexOf时相同)
//Look for the a among the xes(//在xes中查找a)
test('xxx');(试验( 'XXX');) test('axx');(试验( 'AXX');) test('xax');(试验( 'XAX');) test('xxa');(试验( 'XXA');) test('axa');(试验( 'AXA');) test('xaa');(试验( '的Xaa');) test('aax');(试验( 'AAX');) test('aaa');(试验( 'AAA');)
ask by Pat translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…