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"], ...] 
                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.
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 );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With