Replace a string slice
This seems absurdly simple, but I'm having trouble thinking of a clean way to do this.
Consider:
开发者_运维百科var str = "foo bar foo bar foo bar";
I want to replace the second "foo bar" instance (i.e., str.substring(8, 15)
) with an arbitrary string of arbitrary length.
Why not use
var str = "foo bar foo bar foo bar";
str = str.substring(0, 8) + "my new string" + str.substring(15)
You can even generalize with:
var token = "foo bar";
var newStr = "my new string";
var str = "foo bar foo bar foo bar";
str = str.substring(0, token.length+1) +
newStr +
str.substring(token.length*2+1);
I'd typically prefer to use the Array.splice method for this sort of thing:
var str = "foo bar foo bar foo bar".split('');
str.splice(8, 7, 'newstring');
str = str.join('');
//"foo bar newstring foo bar"
If you're going to want to reuse this, then add it to strings:
if (!String.prototype.splice)
{
String.prototype.splice = function(index, howmany, element){
var arr = this.split('');
arr.splice(index, howmany, element);
return arr.join('');
};
}
Of course this is a simple example that only handles a single inserted element. Splice for arrays handles multiple, but as such the strings would just be concatenated anyway, so one element is provided.
Using this method you could call:
a = "foo bar foo bar foo bar".splice( 8, 7, 'newstring' );
//a is now 'foo bar newstring foo bar'
I wrote a prototype method for it:
String.prototype.sliceReplace = function(start, end, repl) {
return this.substring(0, start) + repl + this.substring(end);
};
var s = "12345678";
s.sliceReplace(2,4, "-----"); // "12-----5678"
You could use regex:
"foo bar foo bar foo bar".replace(/foo bar (foo bar)/, '$1 testest'); // foo bar testtest foo bar
"notfoo notbar foo bar foo bar".replace(/foo bar (foo bar)/, '$1 testest'); // notfoo notbar foo bar testtest
or
var token = "foo bar";
var newStr = "new string";
var rg = new RegExp(token + ' (' + token + ')');
"foo bar foo bar foo bar".replace(rg, '$1 ' + newStr);
精彩评论