使用javaScript查找字符串中重复单词每次出现的起始索引的最佳方法
FindIndex(s,kw)应该查找字符串中关键字(kw)每次出现的起始索引使用javaScript查找字符串中重复单词每次出现的起始索引的最佳方法,javascript,Javascript,FindIndex(s,kw)应该查找字符串中关键字(kw)每次出现的起始索引 函数findIndex(秒,千瓦){ var结果=[]; s=”“+s.toLowerCase()+”; kw=”“+kw.toLowerCase()+”; var i=s.indexOf(千瓦); 而(i>=0){ 结果:推(i); i=s.indexOf(kw,i+kw.长度); }; console.log(“索引“+kw+”:”); 对于(变量i=0;i
函数findIndex(秒,千瓦){
var结果=[];
s=”“+s.toLowerCase()+”;
kw=”“+kw.toLowerCase()+”;
var i=s.indexOf(千瓦);
而(i>=0){
结果:推(i);
i=s.indexOf(kw,i+kw.长度);
};
console.log(“索引“+kw+”:”);
对于(变量i=0;i
这是我能让它工作的最好方法,但我不喜欢在两个字符串集前后都要加空格(s=“+s.toLowerCase()+”;kw=“+kw.toLowerCase()+”;
)来排除那些包含搜索词(菠萝等)的词。我尝试使用RegExp(kw=newregexp('\\b'+kw+'\\b'));
但是它不起作用。如果您能想出一个更好的解决方案,我将不胜感激。谢谢!不适用于正则表达式,您需要使用查找匹配索引。但是,要进行多个匹配,您需要使用正则表达式:
function findIndexes(s,kw){
var result = [],
kw = new RegExp('\\b' + kw + '\\b', 'ig'),
// case insensitive and global flags ^^
r;
while (r = kw.exec(s)) {
result.push(r.index);
}
console.log.apply(console, result);
return result;
}
不适用于正则表达式,您需要使用查找匹配索引。但是,要进行多个匹配,您需要使用正则表达式:
function findIndexes(s,kw){
var result = [],
kw = new RegExp('\\b' + kw + '\\b', 'ig'),
// case insensitive and global flags ^^
r;
while (r = kw.exec(s)) {
result.push(r.index);
}
console.log.apply(console, result);
return result;
}
您可以使用
String.prototype.split
将字符串按“
进行拆分,并以这种方式获取单词,然后根据要查找的键检查元素
function getIndexes (str,key) {
var up="toUpperCase",result = [];
str=str.split (" ");
str.unshift(0);
str.reduce (function (index,word) {
if (key[up]() === word[up]())
result.push(index);
return index + word.length + 1;
});
return result;
}
console.log (
getIndexes (
"Apple PEAR banana pineapple STRAWBERRY appLE CrabApple ApPle","apple"
)
); //[0, 39, 55]
这是一个您可以使用
String.prototype.split
将字符串按“
进行拆分,并以这种方式获取单词,然后根据要查找的关键字检查元素
function getIndexes (str,key) {
var up="toUpperCase",result = [];
str=str.split (" ");
str.unshift(0);
str.reduce (function (index,word) {
if (key[up]() === word[up]())
result.push(index);
return index + word.length + 1;
});
return result;
}
console.log (
getIndexes (
"Apple PEAR banana pineapple STRAWBERRY appLE CrabApple ApPle","apple"
)
); //[0, 39, 55]
这是一个