如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
当前回答
正如许多人提到的,原型应该是最好的方法。确保原型出现的时间早于它被使用的时间。
String.prototype.insert = function (x, str) {
return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};
其他回答
更新2016:下面是另一个基于一行RegExp方法的原型函数(在未定义或负索引上提供prepend支持):
/**
* 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"
之前(回到2012年)只是为了好玩的解决方案:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
我们可以同时使用子字符串和切片方法。
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
子字符串方法的唯一问题是它不能与负索引一起工作。它总是从第0位开始取字符串下标。
下面是我写的一个像所有其他编程语言一样的方法:
string .prototype.insert =函数(索引,字符串){ If (index > 0) { 返回。子字符串(0,index) +字符串+ this。substring(指数、this.length); } 返回string + this; }; //使用示例: var something =“你好吗?”; 某事=某事。插入(3,“are”); console.log(东西)
参考:
http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/
正如许多人提到的,原型应该是最好的方法。确保原型出现的时间早于它被使用的时间。
String.prototype.insert = function (x, str) {
return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};
您可以使用regexp在一行代码中轻松完成这一任务
const str = 'Hello RegExp!'; Const index = 6; const insert = 'Lovely '; / /“你好RegExp !”.replace (/ ^ ({6 })(.)/, `$ 1的2美元的); const res = str.replace(新的正则表达式(^(。{${指数 }})(.)`), `$ 1 ${插入}$ 2 '); console.log (res);
“你好,可爱的RegExp!”