我有两个变量,需要将字符串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;
当前回答
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 array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
这样会慢一些,但是会考虑到在an前后增加的空间 另外,你还需要改变position的值(改为2,现在更直观了)
如果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}) /,“一个”);
如果你像这样使用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语句中。
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)
使用ES6字符串字面值,会短得多:
const insertAt = (str, sub, pos) => ' ${str。片(0,pos)} ${子}$ {str.slice (pos)} '; console.log(insertAt('I want apple', ' an', 6)) // log '我想要一个苹果'