我需要在数组中找到单词的索引。但是对于以下场景
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
我如何通过正则表达式来搜索字符串“fine”以获取数组的函数indexOf?
你也可以在单词数组上使用过滤器,
http://jsfiddle.net/6Nv96/
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;
}
});
后 .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
如果你正在使用 underscore.js 库然后你可以使用_.findIndex()方法。
var targetStr = 'string2';
var r = _.findIndex(['string1', 'string2'], function(str){
return targetStr.indexOf(str) >= 0;
});
//Index is always >=0
if(r >= 0){
//result found
}
如果源字符串可能很复杂而且不容易被''拆分,那么您可能应该使用更强大的方法。如果您不介意包含外部库,则可以使用 NAT-JS 标记化源字符串。这是一个例子:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example 04 - Word Index</title>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>-->
<script src="../js/lib/jquery-1.9.0.min.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/qunit/1.12.0/qunit.min.js"></script>-->
<script src="../js/lib/nat.js"></script>
</head>
<body>
<h1>Example 04 - Word Index</h1>
<p>
You can use nat-js to tokenize a text and build some logic over it.
</p>
<script>
$(document).ready(function(){
var searchString = 'fine';
var sourceString = 'hello how are you r u fineOr not .Why u r not fine.Please tell wats makes u notfiness';
var tkz = new nat.tokenizer();
var tokens = tkz.execute(sourceString);
var i = 0;
var result = [];
for(var t in tokens) {
var tk = tokens[t];
if ( tk.value.indexOf(searchString)>=0 ) {
result.push({
what: tk.value,
where: i
});
}
i++;
}
result.forEach(function(r) {
console.log('found ' + r.what + ' in ' + r.where);
});
});
</script>
</body>
</html>
为了解决OP,我觉得还没有完成,这里是一个通过正则表达式使用精简迭代的indexOf的循环方式:
var arr = ['foo','bar','this','that','another'];
var re = /^[Tt]hi[a-z]$/; // expected match is 'this'
var ind = arr.indexOf((function(){
var i;
for(i in arr)
if(re.test(arr[i]))
return arr[i];
})());
// ind = 2 which is accurate
re = /i_dont_exist/; // expected not to match
ind = arr.indexOf((function(){
var i;
for(i in arr)
if(re.test(arr[i]))
return arr[i];
})());
// ind = -1, also accurate
另一个未被提及的替代方案如下:
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(" ");
function findIndex(splitStr){
return splitStr.findIndex(function (element) {
return element.indexOf('fine') === 0;
})
}
console.log(findIndex(splitStr)); // 6
说明:
该 findIndex 方法迭代数组的每个元素,并在提供的匿名函数返回true时返回所需元素的索引。
element.indexOf 在这种情况下,将每个元素作为一个字符串进行计算并进行求值 0 一旦它到达一个元素,其中出现所需的单词,即('精细')。一旦评估为0并与0比较,将返回true。这将使 findIndex 将函数求值的元素的索引返回true。