Answers:
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.slice(0, position + 1), b, a.slice(position)].join('');
给操作人员“我要一个苹果”而不是“我要一个苹果”。
var output = a.substring(0, position) + b + a.substring(position);
编辑:替换为.substr
,.substring
因为.substr
现在它是旧版功能(每个https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
String.prototype.substr
现在已弃用。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
.substring
您可以将此函数添加到字符串类
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");
像这样使用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语句中。
该Underscore.String图书馆,做了功能插入
insert(string,index,substring)=>字符串
像这样
insert("Hello ", 6, "world");
// => "Hello world"
尝试
a.slice(0,position) + b + a.slice(position)
或正则表达式解决方案
"I want apple".replace(/^(.{6})/,"$1 an")
好吧,只是一个很小的变化,就是因为上面的解决方案输出
“我想要一个苹果”
代替
“我想要一个苹果”
要获得输出为
“我想要一个苹果”
使用以下修改的代码
var output = a.substr(0, position) + " " + b + a.substr(position);