我有两个变量,需要将字符串b插入字符串a,在position表示的点上。我想要的结果是“我想要一个苹果”。我如何用JavaScript做到这一点?

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

当前回答

下划线。String库有一个插入函数

Insert (string, index, substring) =>字符串

像这样

insert("I want apple", 6, " an");
// => "I want an apple"

其他回答

如果ES2018的回溯可用,还有一个regexp解决方案,使用它来“替换”第n个字符后的零宽度位置(类似于@Kamil kiezczewski的方法,但没有将初始字符存储在捕获组中):

"I want apple".replace(/(?<=^.{6})/, " an")

var a =“我想要苹果”; Var b = " an"; Var位置= 6; var r = a.replace(新RegExp (`(?<=^.{${ 位置}})),b); console.log (r); console.log(“我想要苹果”.replace(/(? < = ^{6}) /,“一个”);

try

a.slice(0,position) + b + a.slice(position)

var a =“我想要苹果”; Var b = " an"; Var位置= 6; Var r= a.slice(0,位置)+ b + a.slice(位置); console.log (r);

或regexp解决方案

"I want apple".replace(/^(.{6})/,"$1 an")

var a =“我想要苹果”; Var b = " an"; Var位置= 6; var r = a.replace(新RegExp(' ^({${职位}})),“$ 1”+ b); console.log (r); console.log(“我想要苹果”.replace(/ ^({6}) /,“1美元”));

快速修复!如果你不想手动添加空格,你可以这样做:

var a =“我想要苹果”; Var b = "an"; Var位置= 6; Var输出= [a.]Slice (0, position + 1), b, a.slice(position)].join("); console.log(输出);

(编辑:我看到上面已经回答了这个问题,对不起!)

var a =“我想要苹果”; Var b = " an"; Var位置= 6; Var输出= [a.]Slice (0, position), b, a.slice(position)].join("); console.log(输出);


可选:作为String的原型方法

下面可以使用一个可选的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.substr(0, position) + " " + b + a.substr(position);