如何在另一个字符串的特定索引处插入字符串?
var txt1 = "foo baz"
假设我想在“foo”之后插入“bar”,我该如何实现呢?
我想到了substring()
,但必须有一种更直接的方式。
答案 0 :(得分:329)
在特定索引处插入(而不是在第一个空格字符处)必须使用字符串切片/子字符串:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
答案 1 :(得分:226)
您可以将自己的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
为绝对值。
答案 2 :(得分:125)
试试这个。 这是我编写的一种方法,其行为与所有其他编程语言一样。
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
使用示例:
var something = "How you?";
something = something.insert(3, " are");
Simples。
参考: http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/
答案 3 :(得分:60)
只需制作以下功能:
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 !
答案 4 :(得分:15)
2016年更新:这是基于单行RegExp
方法的另一个 just-for-fun (但更严重!)原型函数(带有prepend)支持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"
上一页(回到2012年)只是为了好玩的解决方案:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
答案 5 :(得分:10)
如果有人正在寻找在字符串中的多个索引处插入文本的方法,请尝试这样做:
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>!"
答案 6 :(得分:9)
这基本上是在做@ 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);
};
用例: 假设您使用命名约定具有完整大小的图像,但无法更新数据以提供缩略图URL。
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
答案 7 :(得分:8)
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('');
答案 8 :(得分:7)
根据您当前的示例,您可以通过
获得结果var txt2 = txt1.split(' ').join(' bar ')
或
var txt2 = txt1.replace(' ', ' bar ');
但考虑到你可以做出这样的假设,你也可以直接跳到Gullen的例子。
在你真的无法做出基于字符索引的假设的情况下,我真的会选择子字符串解决方案。
答案 9 :(得分:5)
function insertString(string, insertion, place) {
return string.replace(string[place] + string[place + 1], string[place] + insertion + string[place + 1])
}
所以,对你来说,它是insertString("foo baz", "bar", 3);
显然,这将是一个使用的颜色,因为你必须每次都为你的函数提供你的字符串,但目前我不知道如何将它变成像string.replace(insertion, place)
更容易的东西。不过,这个想法仍然存在。
答案 10 :(得分:4)
您可以使用带有动态模式的正则表达式。
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
输出:
"something "
这将替换字符串text.length
开头的output
个空格字符。
RegExp
表示^\
- 行\s
任意空格字符的开头,重复{n}
次,在本例中为text.length
。在使用字符串构建此类模式时,使用\\
到\
转义反斜杠。
答案 11 :(得分:4)
我知道这是一个旧线程,但是,这是一种非常有效的方法。
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
这样做的好处是它可以强制节点内容。因此,如果此节点已经在DOM上,则无需使用任何查询选择器或更新innerText。更改将由于其绑定而反映出来。
您是否需要一个字符串,只需访问节点的文本内容属性即可。
tn.textContent
#=> "I am just trying to help"
答案 12 :(得分:3)
另一个解决方案,将字符串剪成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);
答案 13 :(得分:3)
好吧,我们可以同时使用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位开始获取字符串索引。
答案 14 :(得分:1)
我想分别比较使用Base33和user113716的使用子字符串的方法和使用slice的方法,以做到这一点,我写了一些代码
也看看这个performance comparison, substring, 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的字符串上)
答案 15 :(得分:1)
您可以在一行代码中使用regexp轻松完成
const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ insert }$2`);
//< "Hello Lovely RegExp!"
答案 16 :(得分:1)
此方法的好处有两个:
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
答案 17 :(得分:0)
采取解决方案。我已经以一种简单的格式编写了此代码:
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;
}
答案 18 :(得分:0)
使用ramda:
import { pipe, split, insert, join } from 'ramda';
const insertAtIndex = (strToInsert, index, str) =>
pipe(split(''), insert(index, strToInsert), join(''))(str)