在特定索引处插入字符串

Jie*_*eng 294 javascript string

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

 var txt1 = "foo baz"
Run Code Online (Sandbox Code Playgroud)

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

我想到了substring(),但必须有一个更简单,更直接的方式.

Tim*_*own 358

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

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
Run Code Online (Sandbox Code Playgroud)

  • @ Mr.Polywhirl:不.这个问题没有提及需要这样做. (10认同)
  • ES6是否提供更好的选择?至少可以使用字符串插值,比如`\`$ {txt1.slice(0,3)} bar $ {txt1.slice(3)} \`` (8认同)
  • @AlejandroSalamancaMazuelo:`substring`在这里没问题.我更喜欢`slice`,因为它更灵活(负指数,例如``foo baz".slice(1,-2)`).对于那些值得的东西,它也略短一些. (4认同)
  • 为什么不是子串? (3认同)
  • 这不使用 [above; 中包含的“删除”功能;最佳答案](http://stackoverflow.com/a/4314050/1762224)... (2认同)

use*_*716 241

你可以把你自己的原型splice()变成String.

填充工具

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));
    };
}
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)


编辑:修改它以确保它rem是绝对值.

  • 我知道这是从2010年开始的,但是下面的`slice`解决方案更好更简单.(拼接是破坏性的,切片不是,最好避免修改"你不知道的对象").这个解决方案绝对不应该是第一个可见的答案,即使它当时可能有意义. (6认同)
  • @EirikBirkeland:字符串是不可变的.上面的代码不会修改任何对象.无论哪种方式,你不修改*"你不知道的对象*"的概念将排除数组变异方法.你说你宁愿做`my_array [my_array.length] = item`而不是`my_array.push(item)`? (5认同)
  • 对不起,我的意思是"你不拥有的物品".在这种情况下你对'拼接'是正确的; 确实字符串是不可变的.出于这个原因,我认为`splice`是一个糟糕的关键词选择.我的主要反对意见是反对任意扩展原型,除非它们是标准的polyfills. (4认同)
  • 修改内置对象是非常糟糕的做法。正如我们在 [SmooshGate](https://developers.google.com/web/updates/2018/03/smooshgate) 中看到的那样,随着新功能被添加到语言中,这可能会破坏您的代码,并且如果您不负责任的修改以某种方式得到进入一个在网络上得到广泛采用的库中,它可能会阻止使用简单、清晰的方法名称来实现新功能。 (3认同)

Bas*_*e33 129

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

    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)
Run Code Online (Sandbox Code Playgroud)

使用示例:

    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)
Run Code Online (Sandbox Code Playgroud)

Simples.

参考:http: //coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/

  • 不,不需要。但是“其他”是多余的。 (3认同)

小智 67

只需进行以下功能:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

alert(insert("foo baz", 4, "bar "));
Run Code Online (Sandbox Code Playgroud)

输出:foo bar baz

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

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


Vis*_*ioN 16

更新2016:这是另一个基于单线程方法的有趣(但更严重!)原型功能RegExp(前置支持undefined或负面index):

/**
 * 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"
Run Code Online (Sandbox Code Playgroud)

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

var index = 4,
    what  = 'bar ';

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


Rya*_*Ore 11

这基本上是在做@ 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);
};
Run Code Online (Sandbox Code Playgroud)

使用案例:假设您使用命名约定具有完整大小的图像,但无法更新数据以提供缩略图URL.

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

//    result:  '/images/myimage_thm.jpg'
Run Code Online (Sandbox Code Playgroud)

  • 不需要像这样修改内置对象的原型。糟糕的形式。 (2认同)

Jak*_*ler 10

如果有人正在寻找在字符串中的多个索引处插入文本的方法,请尝试这样做:

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

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

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

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
Run Code Online (Sandbox Code Playgroud)


use*_*521 9

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('');
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*und 8

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

var txt2 = txt1.split(' ').join(' bar ')
Run Code Online (Sandbox Code Playgroud)

要么

var txt2 = txt1.replace(' ', ' bar ');
Run Code Online (Sandbox Code Playgroud)

但考虑到你可以做出这样的假设,你也可以直接跳到Gullen的例子.

在你真的无法做出基于字符索引的假设的情况下,那么我真的会选择子串解决方案.


Mad*_*adi 7

您可以通过一行代码轻松地使用正则表达式来完成此操作

const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
    
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
    
console.log(res);
Run Code Online (Sandbox Code Playgroud)

“你好,可爱的正则表达式!”


Seb*_*oll 6

我知道这是一个旧线程,但是,这是一个非常有效的方法。

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");
Run Code Online (Sandbox Code Playgroud)

这样做的好处在于它强制节点内容。所以如果这个节点已经在 DOM 上,你就不需要使用任何查询选择器或更新 innerText。由于其具有约束力,这些更改将反映出来。

如果您需要一个字符串,只需访问节点的文本内容属性。

tn.textContent
#=> "I am just trying to help"
Run Code Online (Sandbox Code Playgroud)


kam*_*mal 6

好吧,我们可以同时使用 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.substr(index);

    return string + this;
};


console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
Run Code Online (Sandbox Code Playgroud)

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


Que*_*lef 5

function insertString(string, insertion, place) {
  return string.replace(string[place] + string[place + 1], string[place] + insertion + string[place + 1])
}
Run Code Online (Sandbox Code Playgroud)

所以,对你来说 insertString("foo baz", "bar", 3);

显然,这将是一种绘画,因为您每次都必须向函数提供字符串,但是目前我不知道如何使它变成更容易的东西string.replace(insertion, place)。这个想法仍然存在。


Ben*_*Ben 5

  1. 从字符串实例化一个数组
  2. 使用数组#splice
  3. 再次使用Array#join 进行字符串化

这种方法的好处有两个:

  1. 简单的
  2. Unicode 代码点兼容

const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
Run Code Online (Sandbox Code Playgroud)