我有两个变量,需要插入字符串b转换为字符串a在所代表的点position。我正在寻找的结果是“我想要一个苹果”。我怎样才能用 JavaScript 做到这一点?
var a = 'I want apple';
var b = ' an';
var position = 6;
我有两个变量,需要插入字符串b转换为字符串a在所代表的点position。我正在寻找的结果是“我想要一个苹果”。我怎样才能用 JavaScript 做到这一点?
var a = 'I want apple';
var b = ' an';
var position = 6;
var a = "I want apple";
var b = " an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
以下内容可用于text在另一个字符串中拼接到所需的index,并带有可选removeCount参数。
if (String.prototype.splice === undefined) {
  /**
   * Splices text within a string.
   * @param {int} offset The position to insert the text at (before)
   * @param {string} text The text to insert
   * @param {int} [removeCount=0] An optional number of characters to overwrite
   * @returns {string} A modified string containing the spliced text.
   */
  String.prototype.splice = function(offset, text, removeCount=0) {
    let calculatedOffset = offset < 0 ? this.length + offset : offset;
    return this.substring(0, calculatedOffset) +
      text + this.substring(calculatedOffset + removeCount);
  };
}
let originalText = "I want apple";
// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var output = a.substring(0, position) + b + a.substring(position);
编辑:替换.substr为.substring因为.substr现在是一个遗留功能(根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
您可以将此函数添加到字符串类
String.prototype.insert_at=function(index, string)
{   
  return this.substr(0, index) + string + this.substr(index);
}
以便您可以在任何字符串对象上使用它:
var my_string = "abcd";
my_string.insertAt(1, "XX");
使用ES6 字符串文字,会更短:
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
    
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
如果您像这样使用indexOf()确定位置,也许会更好:
function insertString(a, b, at)
{
    var position = a.indexOf(at); 
    if (position !== -1)
    {
        return a.substr(0, position) + b + a.substr(position);    
    }  
    return "substring not found";
}
然后像这样调用函数:
insertString("I want apple", "an ", "apple");
请注意,我在函数调用中的“an”之后放置了一个空格,而不是在 return 语句中。