如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
如何在另一个字符串的特定索引处插入一个字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring(),但一定有一个更简单更直接的方法。
当前回答
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
https://jsfiddle.net/gaby_de_wilde/wz69nw9k/
其他回答
这基本上是@Base33所做的,除了我还提供了使用负号从末尾开始计数的选项。有点像substr方法所允许的。
// use a negative index to insert relative to the end of the string.
String.prototype.insert = function (index, string) {
var ind = index < 0 ? this.length + index : index;
return this.substring(0, ind) + string + this.substr(ind);
};
例子: 假设您有使用命名约定的全尺寸图像,但不能更新数据以同时提供缩略图url。
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
对于你当前的例子,你可以用任何一种方法来达到这个结果
var txt2 = txt1.split(' ').join(' bar ')
or
var txt2 = txt1.replace(' ', ' bar ');
但既然你可以做出这样的假设,你不妨直接跳过葛伦的例子。
在这种情况下,除了基于字符索引之外,您真的不能做出任何假设,那么我真的会选择子字符串解决方案。
正如许多人提到的,原型应该是最好的方法。确保原型出现的时间早于它被使用的时间。
String.prototype.insert = function (x, str) {
return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};
我们可以同时使用子字符串和切片方法。
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
子字符串方法的唯一问题是它不能与负索引一起工作。它总是从第0位开始取字符串下标。
您可以将正则表达式与动态模式一起使用。
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
输出:
"something "
这将替换文本。字符串输出开头的空白字符的长度。 RegExp表示^\ -行首任意空格字符,重复{n}次,在本例中为text.length。在用字符串构建这种模式时,使用\\来转义反斜杠。