搜索javascript字符串并获取单词索引而不是char

时间:2016-07-12 19:42:17

标签: javascript jquery regex string search

我想在javascript字符串中搜索并通过单词索引获取所有字符串,例如:

var str = 'Hello this is my this is world'
myFindWordIndex(str, 'this is') ==> [1, 4]

(搜索字符串出现两次,一次从索引1开始,一次从索引4开始) 解决方案可以使用JQuery

4 个答案:

答案 0 :(得分:1)

我会将您尝试查找的短语和您尝试在其中找到的单词分开。然后,只需检查短语是否包含搜索短语的每一部分。



import sys
... all your other imports...

sys.path.insert("..", 0)
try:
    import my_module
except:
    raise




答案 1 :(得分:0)

使用How to find indices of all occurrences of one string in another in JavaScript?中的功能进行多重搜索

function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, searchStrLen = searchStr.length;
    var index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

function myFindWordIndex(str, search_str) {
    var res = [];
    $.each(getIndicesOf(search_str, str, true), function(i, v) {
        res.push(str.slice(0, v).split(' ').length)
    });
    return res;
}

答案 2 :(得分:0)

这是使用Lodash.js的一个笨重的解决方案。

function run(str, searchingFor) {
  return _.flatten(
    _.zip(str.split(/\s+/), str.split(/\s+/))
  )
  .slice(1, -1)
  .join(' ')
  .match(/\w+\s+\w+/g)
  .reduce((a, b, i) => {
    return b === searchingFor
      ? a.concat(i)
      : a;
  }, []);
}

这是正在运行......

run('Hello this is my this is world', 'this is');
// => [1, 4]

不理想。不太便携。但它确实有效。

答案 3 :(得分:0)

添加@Mohammad的答案,因为它看起来最干净:

var str = 'Hello this is my this is world'
var pos = myFindWordIndex(str, 'this is');
console.log(pos);

function myFindWordIndex(str, word){
    var arr = [];
    var wordLength = word.split(" ").length;
    var position = 0;
    str.split(word).slice(0, -1).forEach(function(value, i){
        position += value.trim().split(" ").length;
        position += i > 0 ? wordLength : 0;
        arr.push(position); 
    });
    return arr;
}