简体   繁体   English

如何在javascript中的字符串的第二行添加文本?

[英]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.

相关问题 `Phaser.Display.Align.In.Center` 适用于我的文本的第一行,但不能使我的第二行居中。 我如何解决它? - `Phaser.Display.Align.In.Center` works well with the first line of my text but doesn't center my 2nd line. How do I fix it? 如何使用FabricJS在Textbox元素的第二行中选择文本? - How to select text in 2nd line of Textbox element by using FabricJS? 如何在这个基于数学的 JavaScript function 中添加第二个变量? - How to add 2nd var in this math based JavaScript function? 如何在 javascript 中获取字符串的最后第二个元素 - how to get the last 2nd element of a string in javascript Javascript干扰第二SVG线动画 - Javascript interfering with 2nd SVG line animation 从字符串的第 2 行返回值 - Return value from 2nd line in string Reg 表达式 - 在 javascript 中如何获得第二个实例? - Reg Expression - In javascript how can I get the 2nd instance? 如何第二次更改getElementById? - How do I change getElementById 2nd time around? 如何获得第二个定义的单选按钮值? - How do I get the 2nd defined radio button value? 如何阻止emacs缩进javascript逗号分隔列表的第二行(例如array或json)? - How can I stop emacs from indenting the 2nd line of a javascript comma-separated list (e.g. array or json)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM