【问题标题】:regex used in javascript array indexOfjavascript数组indexOf中使用的正则表达式
【发布时间】:2013-12-09 22:44:23
【问题描述】:

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

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?

【问题讨论】:

  • 你不能在那里传递正则表达式,因为 indexOf 不是这样工作的。
  • @CBroe 是的,也许值得提出功能请求? tc39.github.io/process-document

标签: javascript regex arrays


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    .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
    

    【讨论】:

    • 你应该使用reduce而不是创建一个数组,使用forEach,然后推入数组
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      为了解决我觉得还没有完成的 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
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

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

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

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

          【讨论】:

            【解决方案7】:

            如果源字符串很复杂并且不容易被 ' ' 分割,也许你应该使用更健壮的方法。如果您不介意包含一个外部库,您可以使用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>
            

            【讨论】:

              【解决方案8】:

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

              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 在这种情况下将每个元素评估为一个字符串,并且一旦到达所需单词 ie ('fine') 出现的元素,它将评估为 0 .一旦评估为 0 并与 0 比较,将返回 true。这将使 findIndex 返回函数评估为 true 的元素的索引。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-11-23
                • 1970-01-01
                • 2019-10-18
                • 1970-01-01
                • 2021-08-19
                相关资源
                最近更新 更多