1

I would like to search in javascript string and get all string occurrence by word index for example:

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

(two occurrences of the search string, one starts at word index 1 and one starts at index 4) the solution can use JQuery

Roi
  • 23
  • 5

4 Answers4

1

I would split the phrase you're trying to find and where you're trying to find it into words. Then simply check if the phrase contains each piece of the search phrase.

function check(hay, needle, from) {
  var i = 1;
  while (i < needle.length) {
    if (hay[from] != needle[i])
      return false;
    i++;
    from++;
  }
  return true;
}

function myFindWordIndex(str, findme) {
  var indices = [];
  var needle = findme.split(" ");
  var hay = str.split(" ");

  for (var i = 0; i < hay.length - needle.length; i++) {
    if (hay[i] == needle[0] && (needle.length==1||check(hay, needle, i)))
      indices.push(i);
  }
  return indices;
}
var str = 'Hello this is my this is world';

console.log(myFindWordIndex(str, 'this is')); // ==> [1, 4]
Damien Black
  • 5,579
  • 18
  • 24
depperm
  • 10,606
  • 4
  • 43
  • 67
0

using function from How to find indices of all occurrences of one string in another in JavaScript? for multi search

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;
}
Community
  • 1
  • 1
Roi
  • 23
  • 5
0

Here's a clunky solution using 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;
  }, []);
}

Here is it running...

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

Not ideal. Not very portable. But it works.

wpcarro
  • 1,528
  • 10
  • 13
0

adding @Mohammad's answer since it looks the cleanest:

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;
}
Roi
  • 23
  • 5