小编典典

在另一个字符串的 x 位置插入字符串

all

我有两个变量,b需要aposition. 我正在寻找的结果是“我想要一个苹果”。我怎样才能用 JavaScript 做到这一点?

var a = 'I want apple';
var b = ' an';
var position = 6;

阅读 76

收藏
2022-04-24

共1个答案

小编典典

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);

可选:作为 String 的原型方法

以下可用于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; }
2022-04-24