在特定索引处插入字符串
2022-08-29 23:20:06
如何在另一个字符串的特定索引处插入字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了,但一定有更简单、更直接的路。substring()
如何在另一个字符串的特定索引处插入字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了,但一定有更简单、更直接的路。substring()
插入特定索引(而不是在第一个空格字符处)必须使用字符串切片/子字符串:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
你可以把自己的原型设计成 String。splice()
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