I have a string with multiple lines in JavaScript.
How can I insert another string after a specific line, so for example line 2?
Asked
Active
Viewed 543 times
1

Pythonwolf
- 109
- 1
- 9
2 Answers
0
One of the easy solutions can be to use plugin that creates lines for you. Remember that when user changes screen size and your div size changes - lines will be not the same. https://splitting.js.org/
Here is example how to insert element after element in pure javascript How to insert an element after another element in JavaScript without using a library?

Taras
- 1,017
- 2
- 13
0
I think you can use String.split() to convert the whole string into an array based on the line break and then insert the text you want by using Array.splice() method and then join again to get the string with multiple lines.
Live Demo :
const str = 'abc<br>def<br>ghi<br>jkl';
const splittedStr = str.split('<br>');
splittedStr.splice(1, 0, 'alpha');
const finalStr = splittedStr.join('<br>');
document.getElementById('result').innerHTML = finalStr;
<div id="result"></div>

Debug Diva
- 26,058
- 13
- 70
- 123