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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20189148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:58:51  来源:igfitidea点击:

regex used in javascript array indexOf

javascriptregexarrays

提问by Pravin Reddy

I need to find the index of the word in array .But for the following scenario

我需要在数组中找到单词的索引。但是对于以下场景

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

How do I need to pass the regex for searching the string "fine" for the function indexOf of array?

我如何需要传递正则表达式来搜索数组的函数 indexOf 的字符串“fine”?

回答by melc

You can also use filter on the array of words,

您还可以对单词数组使用过滤器,

http://jsfiddle.net/6Nv96/

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

回答by Sarath

After .split(' ')you will get splitStras an array , so you have to loop through that

.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

回答by Mohan Dere

If you are using underscore.jslibrary then you can use _.findIndex() method.

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

回答by user.friendly

To address the OP, which I feel has not been done yet, here's a round-about way to indexOf by regex using a condensed iteration:

为了解决我认为尚未完成的 OP,这是使用压缩迭代通过 regex 进行 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

回答by Jose Miguel Cruz y Celis

Another alternative which has not been metioned is the following:

另一个尚未提及的替代方案如下:

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

Explanation:

解释:

The findIndexmethod iterates over each element of the array and returns the index of the desired element when the anonymous function provided returns true.

所述findIndex在阵列中的每个元素的方法迭代并返回时匿名函数提供返回true所需的元素的索引。

element.indexOfin this case evaluates each element as a string and will evaluate to 0once it reaches an element where the desired word i.e. ('fine') appears. Once evaluated to 0 and compared to 0, will return true. This will make findIndexreturn the index of the element at which the function evaluated to true.

在这种情况下element.indexOf将每个元素评估为一个字符串,一旦它到达出现所需单词即 ('fine') 的元素,它将评估为0。一旦评估为 0 并与 0 比较,将返回 true。这将使findIndex返回函数评估为 true 的元素的索引。

回答by tibetty

If you don't care much about the performance, here is a solution

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

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

回答by jamess

The only ES6 answers here continue to use regular expressions, but that is not necessary. If regexps are your performance concern, you can avoid them:

这里唯一的 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}`);

Here is a codepen that demonstrates this: https://codepen.io/sidewayss/pen/LYEpmwX

这是一个演示这一点的代码笔:https://codepen.io/sidewayss/pen/LYEpmwX

There might be more efficient ways than .reverse(), and you can declare a function if you prefer that to 2 duplicate arrow functions. But this eliminates regexp entirely and should perform well.

可能有比 更有效的方法.reverse(),如果您更喜欢 2 个重复的箭头函数,则可以声明一个函数。但这完全消除了正则表达式并且应该表现良好。

回答by Erick

If source string can be complex and not easilly splitted by ' ', maybe you should use a more robust approach. If you don't mind to include an external library, you could use nat-jsto tokenize the source string. Here is an example:

如果源字符串可能很复杂并且不容易被“ ”分割,也许您应该使用更强大的方法。如果您不介意包含外部库,则可以使用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>