UPDATE 2016: Hier ist eine weitere nur zum Spaß (aber seriöser!) Prototyp-Funktion auf der Grundlage eines Einzeilers RegExp
Ansatz (mit Prepend-Unterstützung bei undefined
oder negativ index
):
/**
* Insert `what` to string at position `index`.
*/
String.prototype.insert = function(what, index) {
return index > 0
? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
: what + this;
};
console.log( 'foo baz'.insert('bar ', 4) ); // "foo bar baz"
console.log( 'foo baz'.insert('bar ') ); // "bar foo baz"
Vorherige (zurück bis 2012) nur so zum Spaß Lösung:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"