【问题标题】:Search for all instances of a string inside a string在字符串中搜索字符串的所有实例
【发布时间】:2011-03-22 21:48:28
【问题描述】:

您好,我正在使用 indexOf 方法来搜索一个字符串是否存在于另一个字符串中。但我想得到字符串在哪里的所有位置?有什么方法可以获取字符串存在的所有位置吗?

<html>
<head>
    <script type="text/javascript">
        function clik()
        {
            var x='hit';
            //document.getElementById('hideme').value ='';
            document.getElementById('hideme').value += x;
            alert(document.getElementById('hideme').value);
        }

        function getIndex()
        {
            var z =document.getElementById('hideme').value;
            alert(z.indexOf('hit'));
        }
    </script>
</head>
<body>
    <input type='hidden' id='hideme' value=""/>
    <input type='button' id='butt1' value="click click" onClick="clik()"/>
    <input type='button' id='butt2' value="clck clck" onClick="getIndex()"/>
</body>
</html>

有没有获取所有位置的方法?

【问题讨论】:

    标签: javascript search indexof


    【解决方案1】:

    尝试类似:

    var regexp = /abc/g;
    var foo = "abc1, abc2, abc3, zxy, abc4";
    var match, matches = [];
    
    while ((match = regexp.exec(foo)) != null) {
      matches.push(match.index);
    }
    
    console.log(matches);
    

    【讨论】:

    • 我很容易忘记匹配对象具有“索引”属性!
    【解决方案2】:

    这是一个工作函数:

    function allIndexOf(str, toSearch) {
        var indices = [];
        for(var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {
            indices.push(pos);
        }
        return indices;
    }
    

    使用示例:

    > allIndexOf('dsf dsf kfvkjvcxk dsf', 'dsf');
    [0, 4, 18]
    

    【讨论】:

      【解决方案3】:

      我不知道是否有内置函数可以做到这一点。你可以在一个简单的循环中做到这一点:

      function allIndexes(lookIn, lookFor) {
          var indices = new Array();
          var index = 0;
          var i = 0;
          while(index = lookIn.indexOf(lookFor, index) > 0) {
              indices[i] = index;
              i++;
          }
          return indices;
      }
      

      【讨论】:

      • 你的代码不起作用: - 如果找到一个术语,你有一个无限循环(indexOf 从找到的位置开始) - 它总是会在你测试时忽略第一次出现 if indexOf(.. .) > 0 而不是 >= 0
      【解决方案4】:

      您可以使用 indexOf('searchstring', ),使用“上次回合”返回的索引 + 1,直到返回 -1。

      【讨论】:

        【解决方案5】:

        这是一个正则表达式的方法:

        function positions(str, text) {
          var pos = [], regex = new RegExp("(.*?)" + str, "g"), prev = 0;
          text.replace(regex, function(_, s) {
            var p = s.length + prev;
            pos.push(p);
            prev = p + str.length;
          });
          return pos;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-30
          相关资源
          最近更新 更多