JavaScript数组indexOf中使用的正则表达式

18

我需要在数组中找到单词的索引,但是对于以下情况:

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

我需要为数组函数indexOf搜索字符串"fine"时如何传递正则表达式?


1
你不能在那里传递一个正则表达式,因为这不是indexOf的工作方式。 - CBroe
@CBroe 是的,也许值得提出一个功能请求?https://tc39.github.io/process-document/ - Michael W. Czechowski
8个回答

10

您还可以在单词数组上使用筛选器,

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;
    }
});

3

.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

1
你应该使用reduce而不是创建一个数组,使用forEach然后将其推入数组。 - Jonah

2

如果您正在使用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
}

2
如果您不太关心性能,这里有一个解决方案。

const str = "hello how are you r  u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
const splitStr = str.split(" ");
let i = splitStr.findIndex(v => /.*fine.*/.test(v));
let k = splitStr.length - splitStr.reverse().findIndex(v => /.*fine.*/.test(v));
console.log(--i);
console.log(--k);


2
这里唯一的 ES6 回答继续使用正则表达式,但这并不是必要的。如果正则表达式是您关注的性能问题,则可以避免使用它们:
const str = "hello how are you r  u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
const splitStr = str.split(" ");
let i = splitStr.findIndex(str => str.includes("fine"));
let k = splitStr.length - splitStr.reverse().findIndex(str => str.includes("fine"));
console.log(`i = ${--i}\nk = ${--k}`);

这是一个演示的 CodePen:https://codepen.io/sidewayss/pen/LYEpmwX 可能有比使用 .reverse() 更有效的方法,如果你更喜欢声明函数而不是两个重复的箭头函数也可以。但这将完全消除正则表达式,并且应该执行得很好。

1
为了解决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

0

还有另一种选择,但尚未提及:

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 将每个元素作为字符串进行评估,并在找到所需单词(即“fine”)的元素时评估为0。一旦评估为0并与0进行比较,就会返回 true。这将使 findIndex 返回函数评估为 true 的元素的索引。


0

如果源字符串很复杂,不容易通过空格分割,那么您应该使用更强大的方法。如果您不介意包含外部库,可以使用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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接