在另一个字符串的x位置插入字符串

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

var a = 'I want apple';
var b = ' an';
var position = 6;
356408 次浏览
var output = a.substring(0, position) + b + a.substring(position);

编辑:将.substr替换为__ABC1,因为.substr现在是一个遗留函数(每个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)

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);


可选:作为String的原型方法

下面可以使用一个可选的removeCount参数,将text拼接到所需的index处的另一个字符串中。

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);
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
这样会慢一些,但是会注意到在an前后增加的空格 同样,你必须改变position的值(到2,现在更直观)

您可以将此函数添加到字符串类

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语句中。

下划线。字符串库有一个执行插入的函数

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

像这样

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

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

var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
console.log(output);

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

使用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'

试一试

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

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"));

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

"I want apple".replace(/(?<=^.{6})/, " 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"));

RegExp替换

var a = 'I want apple';
var b = ' an';
var position = 6;
var output = a.replace(new RegExp(`^(.{${position}})(.*)`), `$1${b}$2`);


console.log(output);

信息: