Pra*_*ddy 14 javascript regex arrays
我需要在数组中找到单词的索引.但是对于以下场景
var str="hello how are you r u fineOr not .Why u r not fine.Please tell wats makes u notfiness".
var splitStr=str.split(" ");
//in splitStr array fineOr is stored at da index of 6.
//in splitStr array notfiness is stored at da index of 18.
var i=splitStr.indexOf("**fine**");
var k=splitStr.lastindexOf("**fine**");
console.log('value i-- '+i); it should log value 6
console.log('value k-- '+k); it should log value 18
Run Code Online (Sandbox Code Playgroud)
我如何传递正则表达式来搜索字符串"fine"以获取数组的函数indexOf?
mel*_*elc 10
你也可以在单词数组上使用过滤器,
var str="hello how are you r u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
var splitStr=str.split(" ");
splitStr.filter(function(word,index){
if(word.match(/fine/g)){/*the regex part*/
/*if the regex is dynamic and needs to be set by a string, you may use RegExp and replace the line above with,*/
/*var pattern=new RegExp("fine","g");if(word.match(pattern)){*/
/*you may also choose to store this in a data structure e.g. array*/
console.log(index);
return true;
}else{
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
之后.split(' ')你将得到splitStr一个数组,所以你必须循环它
var str="hello how are you r u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
var splitStr = str.split(" ");
var indexs = [];
splitStr.forEach(function(val,i){
if(val.indexOf('fine') !== -1) { //or val.match(/fine/g)
indexs.push(i);
}
});
console.log(indexs) // [7, 13, 18]
console.log('First index is ', indexs[0]) // 7
console.log('Last index is ', indexs[indexs.length-1]) // 18
Run Code Online (Sandbox Code Playgroud)