如何在字符串中获取模式的所有索引
How to get all indexes of a pattern in a string?
我想要这样的东西:
"abcdab".search(/a/g) //return [0,4]
有可能吗?
您可以多次使用RegExp#exec
方法:
var regex = /a/g;
var str = "abcdab";
var result = [];
var match;
while (match = regex.exec(str))
result.push(match.index);
alert(result); // => [0, 4]
助手功能:
function getMatchIndices(regex, str) {
var result = [];
var match;
regex = new RegExp(regex);
while (match = regex.exec(str))
result.push(match.index);
return result;
}
alert(getMatchIndices(/a/g, "abcdab"));
您可以使用/滥用替换函数:
var result = [];
"abcdab".replace(/(a)/g, function (a, b, index) {
result.push(index);
});
result; // [0, 4]
函数的自变量如下:
function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^'d]*)('d*)([^'w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
如果只想查找简单字符或字符序列,可以使用indexOf
[MDN]:
var haystack = "abcdab",
needle = "a"
index = -1,
result = [];
while((index = haystack.indexOf(needle, index + 1)) > -1) {
result.push(index);
}
您可以获得所有匹配索引,如下所示:
var str = "abcdab";
var re = /a/g;
var matches;
var indexes = [];
while (matches = re.exec(str)) {
indexes.push(matches.index);
}
// indexes here contains all the matching index values
在此处进行演示:http://jsfiddle.net/jfriend00/r6JTJ/
非正则表达式变体:
var str = "abcdabcdabcd",
char = 'a',
curr = 0,
positions = [];
while (str.length > curr) {
if (str[curr] == char) {
positions.push(curr);
}
curr++;
}
console.log(positions);
http://jsfiddle.net/userdude/HUm8d/
另一个非正则表达式解决方案:
function indexesOf(str, word) {
const split = str.split(word)
let pointer = 0
let indexes = []
for(let part of split) {
pointer += part.length
indexes.push(pointer)
pointer += word.length
}
indexes.pop()
return indexes
}
console.log(indexesOf('Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate', 'JavaScript'))
基于@jfriend00答案,但已整理:
const getAllIndices = (str, strToFind) => {
const regex = RegExp(strToFind, 'g')
const indices = []
let matches
while (matches = regex.exec(str)) indices.push(matches.index)
return indices
}
console.log(getAllIndices('hello there help me', 'hel'))
console.log(getAllIndices('hello there help me', 'help'))
console.log(getAllIndices('hello there help me', 'xxxx'))
相关文章:
- 名称输入的索引
- Javascript,访问一个主要对象模块模式中的每个对象
- 在jQuery中获取表的行索引
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 测试索引值是否等于某个数字的倍数
- 循环遍历数组中的特定索引
- 按照选项卡索引的顺序循环一个jQuery选择
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 在JavaScript中通过索引从对象数组中获取值
- javascript模式下的asp.net网格视图获胜'不要执着于改变索引
- 在模式窗口中显示页面上单击的值(链接)以及索引值
- 如何在字符串中获取模式的所有索引
- 带有引导程序弹出模式菜单的选项卡索引
- Rails Rendering从索引页以Bootstrap模式显示
- 当字符匹配模式时从数组返回索引
- 在JavaScript ES6中使用Object作为索引数组是一个好模式吗?
- 嵌套模式字段上的Mongoose文本索引
- 在字符串中查找所有匹配的正则表达式模式和匹配的索引
- 在引用另一个模式的MongoDB模式上创建一个文本索引