是否有一种方法来检索(开始)字符的位置在一个正则匹配()在Javascript的结果字符串?
当前回答
这是我想到的:
//查找引用文本的开始和结束位置 //双引号或单引号,支持转义字符,如\" \' Var STR = "这是一个带引号的字符串,因为你可以'读'"; var型 = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/ igm; While (match = pat .exec(str)) { console.log(匹配。index + ' ' + pat . lastindex); }
其他回答
我很幸运地使用了这个基于matchAll的单行解决方案(我的用例需要一个字符串位置数组)
let regexp = /bar/g;
let str = 'foobarfoobar';
let matchIndices = Array.from(str.matchAll(regexp)).map(x => x.index);
console.log(matchIndices)
输出:[3,9]
function trimRegex(str, regex){
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd
or
function trimChar(str, trim, req){
let regex = new RegExp('[^'+trim+']');
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd
这是我最近发现的一个很酷的功能,我在主机上尝试了一下,似乎很管用:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
返回:"border 6 bottom 13 left 18 radius"
看来这就是你要找的东西。
这个成员fn返回String对象中输入单词的以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 ) );
您也可以输入正则表达式:
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));
推荐文章
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- PowerShell和-contains操作符
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?