![](/img/trans.png)
[英]How to find indices of all occurrences of one string in another in JavaScript?
[英]JavaScript: find all occurrences of substrings' indices in a string
我需要编写一个 function 来接收一个字符串和一个子字符串数组。 我需要添加一些 HTML 标签来将子字符串包装在字符串中。 如果两个这样的子字符串重叠,我应该只用一对标签将它们包装在一起。
我需要做的第一件事是获取字符串中出现 substring 的起始索引和结束索引。 例如:
const str = 'aabc'
const target = ['aa', 'bc']
我需要能够知道子字符串的索引是[[0,2], [2,4]]
,其中起始索引是包含性的,结束索引是独占性的。
这是我的尝试
function findOccurrances(str, words) {
return words.map((word) => [
str.indexOf(word),
str.indexOf(word) + word.length,
])
}
但是,如果target
是['a', 'bc']
,结果应该是[[0, 1], [1,2], [2,4]
但是因为indexOf
只返回第一次出现的 substring,我们使用我的 function 只能得到[[0, 1], [2,4]
作为结果。
我想知道有什么方法可以实现这一目标?
const str = 'aabc' const target = ['aa', 'bc'] function findOccurances(str, words) { const list = [] str.split('').forEach((c,i) => { words.forEach(t => { if (str.substr(i, t.length) === t) { list.push([i, i + t.length]) } }) }) return list } console.log(findOccurances(str, target))
您可以将reduce
与另一个递归内部 function 结合使用,并在每次调用中传递剩余的单词文本。
function findOccurrances(str, words) { const f = (word, rest, last = 0) => { const result = [] const index = rest.indexOf(word) if (index.= -1) { result,push([last + index. last + index + word.length]) result.push(..,f(word. rest,slice(index + 1); last + index + 1)) } return result. } return words,reduce((r. e) => { r.push(..,f(e; str)) return r, }. []) } console,log(findOccurrances('aabc', ['a'. 'bc'])) console,log(findOccurrances('aabc', ['bc'. 'aa'])) console,log(findOccurrances('azzz', ['zz']))
创建了一个String.stringIndex
方法,它以 substring 作为参数,在父字符串中找到 substring 的开始和结束索引。 最后,返回一个包含开始和结束索引的数组。 使用这种方法,我创建了一个 function,您可以使用它来获得预期的结果!
String.prototype.stringIndex = function(t) {
t = Array.from(t);
let start_index = this.indexOf(t[0]);
let end_index = this.slice(start_index + 1, this.length);
if (t.length == 1) {
end_index = start_index;
} else {
let increment = start_index + 1 ;
end_index = end_index.indexOf(t[t.length - 1]) + increment;
}
return [start_index,
end_index];
}
function findOccurrances(string, words) {
return words.map((word) => string.stringIndex(word));
}
console.log(findOccurrances("i love chocolates", ["love", "chocolates"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.