sam*_*ami 218 javascript
我有2个vars,需要在这个位置插入b.我正在寻找的结果是"我想要一个苹果".我怎么能用jquery或javascript做到这一点?
var a = 'I want apple';
var b = ' an';
var position = 6;
Run Code Online (Sandbox Code Playgroud)
jAn*_*ndy 352
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);
Run Code Online (Sandbox Code Playgroud)
nic*_*ckf 237
var output = a.substring(0, position) + b + a.substring(position);
Run Code Online (Sandbox Code Playgroud)
jas*_*_89 30
您可以将此函数添加到字符串类
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以在任何字符串对象上使用它:
var my_string = "abcd";
my_string.insertAt(1, "XX");
Run Code Online (Sandbox Code Playgroud)
也许如果你使用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";
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用函数:
insertString("I want apple", "an ", "apple");
Run Code Online (Sandbox Code Playgroud)
注意,我在函数调用中的"an"后面放了一个空格,而不是在return语句中.
使用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'
Run Code Online (Sandbox Code Playgroud)
该Underscore.String图书馆,做了功能插入
insert(string,index,substring)=>字符串
像这样
insert("Hello ", 6, "world");
// => "Hello world"
Run Code Online (Sandbox Code Playgroud)
尝试
a.slice(0,position) + b + a.slice(position)
Run Code Online (Sandbox Code Playgroud)
a.slice(0,position) + b + a.slice(position)
Run Code Online (Sandbox Code Playgroud)
或正则表达式解决方案
"I want apple".replace(/^(.{6})/,"$1 an")
Run Code Online (Sandbox Code Playgroud)
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.slice(0,position) + b + a.slice(position);
console.log(r);
Run Code Online (Sandbox Code Playgroud)
如果 ES2018 的lookbehind可用,还有一个正则表达式解决方案,它利用它在第 N 个字符之后的零宽度位置“替换” (类似于@Kamil Kie?czewski,但不将初始字符存储在捕获组中) :
"I want apple".replace(/(?<=^.{6})/, " an")
Run Code Online (Sandbox Code Playgroud)
"I want apple".replace(/(?<=^.{6})/, " an")
Run Code Online (Sandbox Code Playgroud)