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));
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";
}
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.slice(0,position) + b + a.slice(position);
console.log(r);
或regexp解决方案
"I want apple".replace(/^(.{6})/,"$1 an")
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);
console.log(r);
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);
console.log(r);
console.log("I want apple".replace(/(?<=^.{6})/, " an"));