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

 var txt1 = "foo baz"

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

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


当前回答

这基本上是@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'

其他回答

您可以使用regexp在一行代码中轻松完成这一任务

const str = 'Hello RegExp!'; Const index = 6; const insert = 'Lovely '; / /“你好RegExp !”.replace (/ ^ ({6 })(.)/, `$ 1的2美元的); const res = str.replace(新的正则表达式(^(。{${指数 }})(.)`), `$ 1 ${插入}$ 2 '); console.log (res);

“你好,可爱的RegExp!”

这基本上是@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 str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

以溶液为例。我用简单的格式写了这段代码:

const insertWord = (sentence,word,index) => {
    var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
    var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
    for (var i = 0; i < sliceSentence.length; i++) 
           {
        if (i === index) 
               { // checking if index of array === input index
            for (var j = 0; j < word.length; j++) 
                       {   // if yes we'll insert the word
                output.push(sliceWord[j]); // Condition is true we are inserting the word
                       }
            output.push(" "); // providing a single space at the end of the word
                 }
        output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
            }
    join = output.join(""); // converting an array to string
    console.log(join)
    return join;
}

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

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