Insert a string at a specific index

前端 未结 18 941
眼角桃花
眼角桃花 2020-11-22 14:02

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

18条回答
  •  我在风中等你
    2020-11-22 14:24

    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 tags at certain offsets in a string:

    var text = {
        6: "",
        11: ""
    };
    
    "Hello world!".insertTextAtIndices(text); // returns "Hello world!"
    

提交回复
热议问题