在JavaScript中返回正则expression式匹配()的位置?

有没有一种方法来检索Javascript中正则expression式匹配()的结果string中的(起始)字符位置?

exec返回一个具有index属性的对象:

 var match = /bar/.exec("foobar"); if (match) { alert("match found at " + match.index); } 

而对于多个匹配:

 var re = /bar/g, str = "foobarfoobar"; while ((match = re.exec(str)) != null) { alert("match found at " + match.index); } 

以下是我想到的:

 // Finds starting and ending positions of quoted text // in double or single quotes with escape char support like \" \' var str = "this is a \"quoted\" string as you can 'read'"; var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm; while (match = patt.exec(str)) { console.log(match.index + ' ' + patt.lastIndex); } 

来自developer.mozilla.org关于String .match()方法的文档:

返回的数组有一个额外的input属性,其中包含被parsing的原始string。 另外, 它还有一个索引属性,它表示string中匹配的从零开始的索引

当处理非全局正则expression式(即在你的正则expression式中没有g标志)时, .match()返回的值有一个index属性…所有你需要做的就是访问它。

 var index = str.match(/regex/).index; 

下面是一个示例,显示它的工作原理:

 var str = 'my string here'; var index = str.match(/here/).index; alert(index); // <- 10 

您可以使用String对象的search方法。 这将只适用于第一场比赛,但会做你所描述的。 例如:

 "How are you?".search(/are/); // 4 

这是我最近发现的一个很酷的function,我在控制台上试过了,它似乎工作:

 var text = "border-bottom-left-radius"; var newText = text.replace(/-/g,function(match, index){ return " " + index + " "; }); 

其中返回:“边界6底部13左半径18”

所以这似乎是你在找什么。

该成员fn返回String对象内部input字的基于0的位置(如果有的话)的数组

 String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline ) { /*besides '_word' param, others are flags (0|1)*/ var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ; var _bound = _whole_words ? "\\b" : "" ; var _re = new RegExp( _bound+_word+_bound, _match_pattern ); var _pos = [], _chunk, _index = 0 ; while( true ) { _chunk = _re.exec( this ) ; if ( _chunk == null ) break ; _pos.push( _chunk['index'] ) ; _re.lastIndex = _chunk['index']+1 ; } return _pos ; } 

现在尝试

 var _sentence = "What do doers want ? What do doers need ?" ; var _word = "do" ; console.log( _sentence.matching_positions( _word, 1, 0, 0 ) ); console.log( _sentence.matching_positions( _word, 1, 1, 0 ) ); 

你也可以input正则expression式:

 var _second = "z^2+2z-1" ; console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) ); 

这里得到线性项的位置索引。

 var str = "The rain in SPAIN stays mainly in the plain"; function searchIndex(str, searchValue, isCaseSensitive) { var modifiers = isCaseSensitive ? 'gi' : 'g'; var regExpValue = new RegExp(searchValue, modifiers); var matches = []; var startIndex = 0; var arr = str.match(regExpValue); [].forEach.call(arr, function(element) { startIndex = str.indexOf(element, startIndex); matches.push(startIndex++); }); return matches; } console.log(searchIndex(str, 'ain', true));