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

 var txt1 = "foo baz"

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

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


当前回答

我想比较使用substring的方法和使用slice的方法分别来自Base33和user113716,为此我写了一些代码

还可以看看这个性能比较,子字符串,切片

我使用的代码创建了巨大的字符串,并将字符串“bar”多次插入到巨大的字符串中

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)); }; String.prototype.insert = function (index, string) { if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length); return string + this; }; function createString(size) { var s = "" for (var i = 0; i < size; i++) { s += "Some String " } return s } function testSubStringPerformance(str, times) { for (var i = 0; i < times; i++) str.insert(4, "bar ") } function testSpliceStringPerformance(str, times) { for (var i = 0; i < times; i++) str.splice(4, 0, "bar ") } function doTests(repeatMax, sSizeMax) { n = 1000 sSize = 1000 for (var i = 1; i <= repeatMax; i++) { var repeatTimes = n * (10 * i) for (var j = 1; j <= sSizeMax; j++) { var actualStringSize = sSize * (10 * j) var s1 = createString(actualStringSize) var s2 = createString(actualStringSize) var start = performance.now() testSubStringPerformance(s1, repeatTimes) var end = performance.now() var subStrPerf = end - start start = performance.now() testSpliceStringPerformance(s2, repeatTimes) end = performance.now() var splicePerf = end - start console.log( "string size =", "Some String ".length * actualStringSize, "\n", "repeat count = ", repeatTimes, "\n", "splice performance = ", splicePerf, "\n", "substring performance = ", subStrPerf, "\n", "difference = ", splicePerf - subStrPerf // + = splice is faster, - = subStr is faster ) } } } doTests(1, 100)

性能上的一般差异充其量是边际的,两种方法都工作得很好(即使在长度~~ 12000000的字符串上)

其他回答

您可以将正则表达式与动态模式一起使用。

var text = "something";
var output = "                    ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);

输出:

"something      "

这将替换文本。字符串输出开头的空白字符的长度。 RegExp表示^\ -行首任意空格字符,重复{n}次,在本例中为text.length。在用字符串构建这种模式时,使用\\来转义反斜杠。

只需制作如下函数:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

然后像这样使用:

alert(insert("foo baz", 4, "bar "));

输出:foo bar baz

它的行为完全像c# (Sharp) String。插入(int startIndex,字符串值)。

注意:这个insert函数将字符串值(第三个参数)插入到字符串str(第一个参数)中指定的整型索引(第二个参数)之前,然后返回新的字符串而不改变str!

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

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

您可以将自己的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是一个绝对值。

正如许多人提到的,原型应该是最好的方法。确保原型出现的时间早于它被使用的时间。

String.prototype.insert = function (x, str) {
    return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};