如何在另一个字符串的特定索引处插入一个字符串?

 var txt1 = "foo baz"

假设我想在“foo”之后插入“bar”,我该如何实现呢?

我想到了substring(),但一定有一个更简单更直接的方法。


当前回答

对于你当前的例子,你可以用任何一种方法来达到这个结果

var txt2 = txt1.split(' ').join(' bar ')

or

var txt2 = txt1.replace(' ', ' bar ');

但既然你可以做出这样的假设,你不妨直接跳过葛伦的例子。

在这种情况下,除了基于字符索引之外,您真的不能做出任何假设,那么我真的会选择子字符串解决方案。

其他回答

下面是我写的一个像所有其他编程语言一样的方法:

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/

您可以使用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!”

您可以将自己的splice()原型化为String。

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

例子

String.prototype.splice = function(idx, rem, str) { 返回 this.slice(0, idx) + str + this.slice(idx + Math.abs(rem)); }; var result = “foo baz”.splice(4, 0, “bar ”); document.body.innerHTML = result;“嘟”


EDIT:修改它,以确保rem是一个绝对值。

在特定索引处插入(而不是在第一个空格字符处)必须使用字符串切片/子字符串:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

从字符串实例化一个数组 使用数组#拼接 再次使用array# join进行Stringify

这种方法的好处有两方面:

简单的 Unicode编码点兼容

const pair = Array.from('USDGBP') 对。Splice (3,0, '/') console.log (pair.join ("))