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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4364881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:06:02  来源:igfitidea点击:

Inserting string at position x of another string

javascript

提问by sami

I have two variables and need to insert string binto string aat the point represented by position. The result I'm looking for is "I want an apple". How can I do this with JavaScript?

我有两个变量,需要插入字符串b转换为字符串a在所代表的点position。我正在寻找的结果是“我想要一个苹果”。我怎样才能用 JavaScript 做到这一点?

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

回答by jAndy

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



Optional: As a prototype method of String

可选:作为String的原型方法

The following can be used to splice textwithin another string at a desired index, with an optional removeCountparameter.

以下可用于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; }

回答by nickf

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

Edit: replaced .substrwith .substringbecause .substris now a legacy function(per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)

编辑:替换.substr.substring因为.substr现在是一个遗留功能(根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

回答by jasin_89

You can add this function to string class

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

String.prototype.insert_at=function(index, string)
{   
  return this.substr(0, index) + string + this.substr(index);
}

so that you can use it on any string object:

以便您可以在任何字符串对象上使用它:

var my_string = "abcd";
my_string.insertAt(1, "XX");

回答by paulo62

Maybe it's even better if you determine positionusing indexOf()like this:

如果您像这样使用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";
}

then call the function like this:

然后像这样调用函数:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the "an " in the function call, rather than in the return statement.

请注意,我在函数调用中的“an”之后放置了一个空格,而不是在 return 语句中。

回答by Stefan J

Using ES6 string literals, would be much shorter:

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

回答by svarog

The Underscore.Stringlibrary has a function that does Insert

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

insert(string, index, substring) => string

插入(字符串,索引,子字符串)=> 字符串

like so

像这样

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

回答by Kamil Kie?czewski

try

尝试

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

or regexp solution

或正则表达式解决方案

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

回答by dlauzon

If ES2018's lookbehind is available, one more regexp solution, that makes use of it to "replace" at a zero-width positionafter the Nth character (similar to @Kamil Kie?czewski's, but without storing the initial characters in a capturing group):

如果 ES2018 的lookbehind可用,还有一个正则表达式解决方案,它利用它在第 N 个字符之后的零宽度位置“替换” (类似于@Kamil Kie?czewski,但不将初始字符存储在捕获组中) :

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

回答by Ravindra Sane

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

This would be slower, but will take care of the addition of space before and after the an Also, you'll have to change the value of position ( to 2, it's more intuitive now)

这会更慢,但会注意在 an 前后添加空间另外,您必须更改 position 的值(改为 2,现在更直观)

回答by K. Yu

Quick fix! If you don't want to manually add a space, you can do this:

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

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

(edit: i see that this is actually answered above, sorry!)

(编辑:我看到这实际上已在上面回答,抱歉!)