Javascript 在特定索引处插入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4313841/
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 11:51:21  来源:igfitidea点击:

Insert a string at a specific index

javascriptstring

提问by Jiew Meng

How can I insert a string at a specific index of another string?

如何在另一个字符串的特定索引处插入一个字符串?

 var txt1 = "foo baz"

Suppose I want to insert "bar " after the "foo" how can I achieve that?

假设我想在“foo”之后插入“bar”,我该如何实现?

I thought of substring(), but there must be a simpler more straight forward way.

我想到了substring(),但必须有更简单更直接的方法。

采纳答案by user113716

You could prototype your own splice()into String.

您可以将自己的原型制作splice()为 String。

Polyfill

填充物

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

Example

例子

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"



EDIT:Modified it to ensure that remis an absolute value.

编辑:修改它以确保它rem是一个绝对值。

回答by Tim Down

Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:

在特定索引处插入(而不是在第一个空格字符处)必须使用字符串切片/子字符串:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

回答by Base33

Here is a method I wrote that behaves like all other programming languages:

这是我编写的一个方法,它的行为与所有其他编程语言一样:

String.prototype.insert = function(index, string) {
  if (index > 0)
  {
    return this.substring(0, index) + string + this.substring(index, this.length);
  }

  return string + this;
};

//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)

Reference:

参考:

回答by Base33

Just make the following function:

只需执行以下功能:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

and then use it like that:

然后像这样使用它:

alert(insert("foo baz", 4, "bar "));

Output: foo bar baz

输出: foo bar baz

It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).

它的行为与 C# (Sharp) String.Insert(int startIndex, string value) 完全一样。

NOTE:This insert function inserts the string value(third parameter) beforethe specified integer index(second parameter) in the string str(first parameter), and then returns the new string without changing str!

注意:此插入函数在字符串str(第一个参数)中指定整数索引(第二个参数)之前插入字符串(第三个参数),然后返回新字符串而不更改str

回答by VisioN

UPDATE 2016:Here is another just-for-fun(but more serious!) prototype function based on one-liner RegExpapproach (with prepend support on undefinedor negative index):

2016 年更新:这是另一个基于单行方法(带有 prepend 支持 on或 negative )的有趣(但更严重!)原型函数:RegExpundefinedindex

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"


Previous (back to 2012) just-for-funsolution:

以前(回到 2012 年)只是为了好玩的解决方案:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

回答by Jake Stoeffler

If anyone is looking for a way to insert text at multiple indices in a string, try this out:

如果有人正在寻找一种在字符串中的多个索引处插入文本的方法,请尝试以下操作:

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

For example, you can use this to insert <span>tags at certain offsets in a string:

例如,您可以使用它<span>在字符串中的某些偏移处插入标签:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"

回答by Ryan Ore

This is basically doing what @Bass33 is doing except I'm also giving the option of using a negative index to count from the end. Kind of like the substr method allows.

这基本上是在做@Bass33 正在做的事情,除了我还提供了使用负索引从末尾开始计数的选项。有点像 substr 方法允许的那样。

// use a negative index to insert relative to the end of the string.

String.prototype.insert = function (index, string) {
  var ind = index < 0 ? this.length + index  :  index;
  return  this.substring(0, ind) + string + this.substring(ind, this.length);
};

Use case: Lets say you have full size images using a naming convention but can't update the data to also provide thumbnail urls.

用例:假设您拥有使用命名约定的全尺寸图像,但无法更新数据以提供缩略图 url。

var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');

//    result:  '/images/myimage_thm.jpg'

回答by dxh

Given your current example you could achieve the result by either

鉴于您当前的示例,您可以通过以下任一方式获得结果

var txt2 = txt1.split(' ').join(' bar ')

or

或者

var txt2 = txt1.replace(' ', ' bar ');

but given that you can make such assumptions, you might as well skip directly to Gullen's example.

但鉴于您可以做出这样的假设,您不妨直接跳到 Gullen 的示例。

In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.

在除了基于字符索引之外你真的无法做出任何假设的情况下,我真的会选择子字符串解决方案。

回答by user40521

my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/

回答by kamal

Well, we can use both the substring and slice method.

好吧,我们可以同时使用 substring 和 slice 方法。

String.prototype.customSplice = function (index, absIndex, string) {
    return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};


String.prototype.replaceString = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;
};


console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers

The only problem of a substring method is that it won't work with a negative index. It's always take string index from 0th position.

子字符串方法的唯一问题是它不适用于负索引。它总是从第 0 个位置获取字符串索引。