小编典典

在特定索引处插入字符串

javascript

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

 var txt1 = "foo baz"

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

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


阅读 267

收藏
2020-04-25

共1个答案

小编典典

您可以将自己的原型制作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) {

    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));

};



var result = "foo baz".splice(4, 0, "bar ");



document.body.innerHTML = result; // "foo bar baz"

编辑: 对其进行了修改,以确保它rem是一个绝对值。

2020-04-25