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


237

我有两个变量,需要在表示的点处将字符串b插入字符串aposition。我正在寻找的结果是“我想要一个苹果”。如何使用JavaScript做到这一点?

var a = 'I want apple';
var b = ' an';
var position = 6;

Answers:


376

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的原型方法

以下内容可用于使用可选参数text在所需的其他字符串内拼接。indexremoveCount

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


3
对于长字符串,此解决方案比nickf的解决方案更快(因为它复制较少)。
pts 2010年

35
此解决方案并不快。我对此感到很好奇,并运行了一个jsperf。这是给以后阅读本文的任何人的说明。 jsperf.com/javascript-string-splice。在最新的FF / Chrome / IE10 / IE9中进行了测试。为了清晰和性能起见,我将使用精益尼克的方法。
junkyspace

3
好吧,那很有可能。答案是将近3年了,当时的大多数浏览器和版本都确实通过Array join(尤其是IE)以更快的速度执行。
jAndy

1
请原谅,我已经回答了这么一个老问题,但是对我来说,应该var output = [a.slice(0, position + 1), b, a.slice(position)].join('');给操作人员“我要一个苹果”而不是“我要一个苹果”。
paulvs 2013年

13
@PaulVon改正它永远不会错,所以无需宽恕。无论如何,我有点不同意。功能上会执行其预期的工作,在另一个字符串中的某个位置插入一个字符串。实际上,插入的字符串应该像“ an”,在这种情况下会更正确。
jAndy 2013年

262
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


47
根据@junkyspace jsperf.com/javascript-string-splice,此答案比jAndy的答案快640倍
Paulo Coghi-恢复莫妮卡

5
String.prototype.substr现在已弃用。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
Tivie

2
substring 在这种情况下,可以直接替代已弃用的产品 substr,因此答案变为:var output = a.substring(0, position) + b + a.substring(position);
海水鱼

它不是严格建议弃用的,而是遗留的,因此,有一个很好的替换建议,因为它很可能已弃用,并由MDN建议使用.substring
froggomad

32

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

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

3
修改本地对象原型是一个坏习惯:stackoverflow.com/questions/14034180/…–
jhujhul

10

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


9

像这样使用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语句中。


2
这不是要求的内容。即使是这种情况,如果您多次出现“ at”子字符串,也将无法正常工作
Elachell 16-10-25

6

Underscore.String图书馆,做了功能插入

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

像这样

insert("Hello ", 6, "world");
// => "Hello world"

不是我本人,而是可能是因为问题中没有提及该图书馆。但是他似乎也没有排除IMO的其他图书馆。
Dennis98 '18

1
即使我不喜欢使用库(除非有必要),我还是投票抵消了
下降的投票

3

尝试

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

或正则表达式解决方案

"I want apple".replace(/^(.{6})/,"$1 an")


2
var array = a.split(' '); 
array.splice(position, 0, b);
var output = array.join(' ');

这会比较慢,但是会照顾到前后的空间。此外,您还必须更改position的值(改为2,现在更直观了)


2

快速解决!如果您不想手动添加空格,则可以执行以下操作:

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

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


2

如果可以使用ES2018的lookbehind,则可以使用另一种正则表达式解决方案,该解决方案将其用于“替换” 第N个字符后的零宽度位置(类似于@KamilKiełczewski的字符,但不将初始字符存储在捕获组中):

"I want apple".replace(/(?<=^.{6})/, " an")


1

好吧,只是一个很小的变化,就是因为上面的解决方案输出

“我想要一个苹果”

代替

“我想要一个苹果”

要获得输出为

“我想要一个苹果”

使用以下修改的代码

var output = a.substr(0, position) + " " + b + a.substr(position);

13
是的,在这种情况下可能并不理想,但是在所有情况下几乎绝对不希望自动添加额外的空间。
尼克

12
正确的解决方案不是在字符串='an'中添加空格,这样您就可以重用该函数
Tosh 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.