Get the positions of the substrings before replacing
If i have the string foo bar foo baz foo
and i want to replace foo
with abcd
, i want to开发者_Go百科 get the offsets of the replaced occurences in the string ([0, 8, 16]
in this example). Ho do i get this positions?
var getPositions = function(str, sub) {
var arr=[], idx=-1;
while ((idx=str.indexOf(sub,idx+1)) > -1) {
arr.push(idx);
}
return arr;
};
getPositions('foo bar foo baz foo', 'foo'); // => [0, 8, 16]
If I'm understanding what you're after, this should work for you
var getPositions = function (find, str) {
var arr = [],
pos = 0,
flen = find.length,
len = str.length, i;
while (pos < len) {
i = str.indexOf(find, pos);
if (i !== -1) {
arr.push(i);
pos = i + flen;
} else {
return arr.length ? arr : false;
}
}
return arr.length ? arr : false;
};
Then call it like getPositions("foo", whateverString);
http://jsfiddle.net/pyVaQ/
Would you consider using regex? This way you wouldn't need to mess around with the overhead of finding the locations of the foo parts. If you absolutely need the positions, this solution is not for you.
var str = 'foo bar foo baz foo';
str = str.replace(/foo/g,'abcd');
alert(str);
精彩评论