Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get indexes for split string

How can I use the str.split() function to get an array of indexes of the matches instead of the actual matches?

e.g.:

var str = "The quick brown fox jumps over the lazy dog."
console.log(str.split(' '));
//["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."] 

//I want to get this output instead for the index positions of the matches
//[0, 4, 10, 16, 20, 26, ...] 

//01234567890123456789012345678901234567890123456789 
//The quick brown fox jumps over the lazy dog.

Even better yet, this 2D array output would be ideal:

//[[0, "The"], [4, "quick"], [10, "brown"], [16, "fox"], [20, "jumps"], [26, "over"], ...] 
like image 776
fortuneRice Avatar asked Jul 13 '11 23:07

fortuneRice


2 Answers

Use this method:

function splitWithIndex(str, delim){
 var ret=[]
 var splits=str.split(delim)
 var index=0
 for(var i=0;i<splits.length;i++){
  ret.push([index,splits[i]])
  index+=splits[i].length+delim.length
 }
 return ret
}

Example:

alert(splitWithIndex(str,' ')) 

EDIT (Dec. 17, 2018): Avoid adding methods to native String object.

like image 162
Peter O. Avatar answered Sep 21 '22 02:09

Peter O.


If all the words are unique, you could do this:

Example: http://jsfiddle.net/rWJ5x/

var str = "The quick brown fox jumps over the lazy dog.";

var arr = str.split(' ');

for( var i = 0, len = arr.length; i < len; i++ ) {
    arr[i] = str.indexOf( arr[i] );
}

If there are repeating words, this should do it:

Example: http://jsfiddle.net/rWJ5x/2/

var str = "The quick brown fox jumps over the lazy brown dog.";
var pos = 0;

var arr = str.split(' ');

for( var i = 0, len = arr.length; i < len; i++ ) {
    var idx = str.indexOf( arr[i] );
    arr[i] = pos = (pos + idx);
    str = str.slice( idx );
}
like image 37
user113716 Avatar answered Sep 18 '22 02:09

user113716