在特定索引处插入字符串

2020/10/02 08:01 · javascript ·  · 0评论

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

 var txt1 = "foo baz"

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

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

您可以将自己的原型制作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));
    };
}

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"

编辑:对其进行了修改,以确保它rem是一个绝对值。

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

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

这是我写的一种方法,其行为与所有其他编程语言类似:

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)

参考:

只需执行以下功能:

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

然后像这样使用它:

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

输出:foo bar baz

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

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

2016年更新:这是基于单线方法的另一个好玩的(但更严重的!)原型函数RegExp(带有prepend supportundefined或negative 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"

上一个(回到2012年)有趣的解决方案:

var index = 4,
    what  = 'bar ';

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

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

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

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

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

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

基本上,这是@ 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);
};

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

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

//    result:  '/images/myimage_thm.jpg'
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/

根据您当前的示例,您可以通过

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

要么

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

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

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

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

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

这样做的好处是可以强制节点内容。因此,如果此节点已经在DOM上,则无需使用任何查询选择器或更新innerText。更改将由于其约束而反映出来。

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

tn.textContent
#=> "I am just trying to help"

好吧,我们可以同时使用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

子字符串方法的唯一问题是它不能与负索引一起使用。总是从第0位开始获取字符串索引。

您可以将正则表达式与动态模式一起使用。

var text = "something";
var output = "                    ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);

输出:

"something      "

这将替换text.length字符串开头的空白字符outputRegExp方法^\-开头的行的\s任何空白字符,反复{n}多次,在这种情况下text.length使用\\\构建这种模式出来的字符串时逃跑反斜杠。

另一个解决方案是,将字符串切成2,然后在中间插入字符串。

var str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

您可以在一行代码中使用regexp轻松完成此操作

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

“您好,RegExp!”

使用切片

您可以使用slice(0,index) + str + slice(index)或者,您可以为其创建方法。

String.prototype.insertAt = function(index,str){
  return this.slice(0,index) + str + this.slice(index)
}
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar

字符串的拼接方法

您可以split()添加主字符串,然后使用正常splice()

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


 var txt1 = "foo baz"

//inserting single string.
console.log(txt1.splice(4,0,"bar ")); //foo bar baz


//inserting multiple strings
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz


//removing letters
console.log(txt1.splice(1,2)) //f baz


//remving and inseting atm
console.log(txt1.splice(1,2," bar")) //f bar baz

在多个索引上应用splice()

该方法采用一个数组数组,每个数组元素代表一个splice()

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


String.prototype.mulSplice = function(arr){
  str = this
  let dif = 0;
  
  arr.forEach(x => {
    x[2] === x[2] || [];
    x[1] === x[1] || 0;
    str = str.splice(x[0] + dif,x[1],...x[2]);
    dif += x[2].join('').length - x[1];
  })
  return str;
}

let txt = "foo bar baz"

//Replacing the 'foo' and 'bar' with 'something1' ,'another'
console.log(txt.splice(0,3,'something'))
console.log(txt.mulSplice(
[
[0,3,["something1"]],
[4,3,["another"]]
]

))

我想分别比较使用Base33和user113716的使用子字符串的方法和使用slice的方法,以实现此目的,我编写了一些代码

也看看这个性能比较,子串,切片

我使用的代码创建了巨大的字符串,并将字符串“ bar”多次插入了巨大的字符串

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

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


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

    return string + this;
};


function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    }
    return s
}


function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")
}

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")
}


function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start = performance.now()
            testSubStringPerformance(s1, repeatTimes)
            var end = performance.now()
            var subStrPerf = end - start

            start = performance.now()
            testSpliceStringPerformance(s2, repeatTimes)
            end = performance.now()
            var splicePerf = end - start

            console.log(
                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster
                )

        }
    }
}

doTests(1, 100)

性能上的一般差异充其量是微不足道的,并且两种方法都可以正常工作(即使在长度约为12000000的字符串上)

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

这种方法的好处有两个:

  1. 简单
  2. 符合Unicode代码点
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))

采取解决方案。我已经以一种简单的格式编写了此代码:

const insertWord = (sentence,word,index) => {
    var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
    var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
    for (var i = 0; i < sliceSentence.length; i++) 
           {
        if (i === index) 
               { // checking if index of array === input index
            for (var j = 0; j < word.length; j++) 
                       {   // if yes we'll insert the word
                output.push(sliceWord[j]); // Condition is true we are inserting the word
                       }
            output.push(" "); // providing a single space at the end of the word
                 }
        output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
            }
    join = output.join(""); // converting an array to string
    console.log(join)
    return join;
}
本文地址:http://javascript.askforanswer.com/zaitedingsuoyinchucharuzifuchuan.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!