[英]How do I add text on the 2nd line of a string in javascript?
Suppose my string is:假设我的字符串是:
var string ="abcd
acdcd
ejhwejeh
kjkjewkjkejw";
and I want to add a text in front of the 2nd line called "hello " so it becomes.我想在名为“hello”的第二行前面添加一个文本,所以它变成了。
string ="abcd
hello acdcd
ejhwejeh
kjkjewkjkejw";
How would I achieve this?我将如何实现这一目标?
Split the string at the newlines with在换行符处拆分字符串
var arr = string.split(/\r?\n/);
That gives you an array with the single words, which you can put together again with the new word.这为您提供了一个包含单个单词的数组,您可以将其与新单词重新组合在一起。
var string2 = '';
for (var i = 1; i < arr.length; i++) {
string2 = string2 + arr[i]
}
string2 = arr[0] + 'hello' + string2
You could split the string with linefeed and change the array with the wanted part and joinf the array to a new string.您可以使用换行符拆分字符串并使用所需部分更改数组并将数组加入新字符串。
var string ="abcd\\nacdcd\\nejhwejeh\\nkjkjewkjkejw", temp = string.split(/\\n/); temp[1] = 'hello ' + temp[1]; console.log(temp.join('\\n'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.