如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
当前回答
您可以将自己的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是一个绝对值。
其他回答
从字符串实例化一个数组 使用数组#拼接 再次使用array# join进行Stringify
这种方法的好处有两方面:
简单的 Unicode编码点兼容
const pair = Array.from('USDGBP') 对。Splice (3,0, '/') console.log (pair.join ("))
我知道这是一个古老的话题,然而,这里有一个真正有效的方法。
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
这样做的好处在于它强制了节点内容。因此,如果该节点已经在DOM上,则不需要使用任何查询选择器或更新innerText。这些变化将反映由于其约束力。
如果需要字符串,只需访问节点的文本内容属性。
tn.textContent
#=> "I am just trying to help"
如果有人正在寻找一种在字符串的多个下标处插入文本的方法,请尝试以下方法:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
例如,你可以使用它在字符串的特定偏移处插入<span>标签:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
我想比较使用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 txt2 = txt1.split(' ').join(' bar ')
or
var txt2 = txt1.replace(' ', ' bar ');
但既然你可以做出这样的假设,你不妨直接跳过葛伦的例子。
在这种情况下,除了基于字符索引之外,您真的不能做出任何假设,那么我真的会选择子字符串解决方案。