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

Javascript 在特定索引处插入字符串,javascript,string,Javascript,String,如何在另一个字符串的特定索引处插入字符串 var txt1 = "foo baz" 假设我想在“foo”之后插入“bar”,我该如何实现呢 我想到了substring(),但必须有一个更简单更直接的方法。根据您当前的示例,您可以通过以下两种方法来实现结果: var txt2 = txt1.split(' ').join(' bar ') 或 但考虑到你可以做出这样的假设,你不妨直接跳到古伦的例子 在除了基于字符索引之外,您真的无法做出任何假设的情况下,我真的会选择子字符串解决方案。在特定索

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

 var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢


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

根据您当前的示例,您可以通过以下两种方法来实现结果:

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

但考虑到你可以做出这样的假设,你不妨直接跳到古伦的例子


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

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

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

您可以将自己的
splice()
原型化为字符串

聚填料 例子
String.prototype.splice=函数(idx、rem、str){
返回this.slice(0,idx)+str+this.slice(idx+Math.abs(rem));
};
var result=“foo baz”。拼接(4,0,“bar”);

document.body.innerHTML=结果;//“foo-bar-baz”
以下是我编写的一个方法,其行为与所有其他编程语言类似:

String.prototype.insert=函数(索引,字符串){
如果(索引>0){
返回this.substring(0,索引)+字符串+this.substr(索引);
}
返回字符串+这个;
};
//使用示例:
var something=“你好吗?”;
某物=某物。插入(3,“是”);

console.log(something)
2016年更新:这里是另一个基于一种线性方法(在
未定义
或负
索引
上具有前置支持)的纯粹为了好玩(但更严肃!)原型函数:


上一个(回到2012年)只是为了好玩的解决方案:

var index = 4,
    what  = 'bar ';

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

另一种解决方案是,将字符串切成两段,并在两段之间插入一条字符串

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

您可以使用带有动态模式的正则表达式

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

"something      "
这将替换字符串
输出
开头空白字符的
文本长度。

RegExp
表示
^\
-行的开头
\s
任何空格字符,重复
{n}
次,在本例中为
text.length
。使用字符串构建此类模式时,请使用
\\
\
转义反斜杠

只需执行以下功能:

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

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

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};
例如,您可以使用它在字符串中的特定偏移处插入
标记:

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

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
var text={
6: "",
11: ""
};
“你好,世界!”。插入文本(文本);//返回“你好,世界!”

这基本上是在做@Base33正在做的事情,除了我还提供了使用负索引从末尾开始计数的选项。有点像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.substr(ind);
};

我知道这是一个古老的思路,但是,这里有一个非常有效的方法

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");
这样做的好处在于它强制节点内容。因此,如果这个节点已经在DOM上,则不需要使用任何查询选择器或更新innerText。这些变化将反映出其约束力

如果需要字符串,只需访问节点的文本内容属性即可

tn.textContent
#=> "I am just trying to help"
使用切片 您可以使用
slice(0,index)+str+slice(index)
。或者您可以为它创建一个方法

String.prototype.insertAt=函数(索引,str){
返回此.slice(0,索引)+str+this.slice(索引)
}

console.log(“foo-bar”.insertAt(4,'baz')//foo-baz-bar
我想分别比较使用substring的方法和使用Base33和user113716中的slice的方法,为此我编写了一些代码

也看看这个

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

if(!String.prototype.splice){
/**
*{JSDoc}
*
*splice()方法通过删除字符串的一个范围来更改字符串的内容
*字符和/或添加新字符。
*
*@this{String}
*@param{number}开始索引,从该索引开始更改字符串。
*@param{number}delCount一个整数,指示要删除的旧字符数。
*@param{string}newSubStr插入的字符串。
*@return{string}具有拼接子字符串的新字符串。
*/
String.prototype.splice=函数(start、delCount、newSubStr){
返回this.slice(0,start)+newSubStr+this.slice(start+Math.abs(delCount));
};
}
String.prototype.splice=函数(idx、rem、str){
返回this.slice(0,idx)+str+this.slice(idx+Math.abs(rem));
};
String.prototype.insert=函数(索引,字符串){
如果(索引>0)
返回this.substring(0,index)+字符串+this.substring(index,this.length);
返回字符串+这个;
};
函数createString(大小){
var s=“”
对于(变量i=0;i对于(var i=1;i那么,我们可以同时使用子字符串和切片方法

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
子字符串方法的唯一问题是它不能与负索引一起工作
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('');
var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");
tn.textContent
#=> "I am just trying to help"
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
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;
}