If I have this HTML code:
<textarea>
line 1 text
line 2 text
line 3 text
line 4 text
line 5 text
</textarea>
How can I insert text after the third line, so my result is this:
<textarea>
line 1 text
line 2 text
line 3 text
this is my new text here!!!!!!!!!
line 4 text
line 5 text
</textarea>
We create a function that takes your text and a line number, splits the current text within the box by the new line character, add in the new text, and update the textarea box.
function addLine(text, line) {
let ta = document.querySelector("textarea"),
split_text = ta.textContent.split(/\n/gmi);
if (line <= split_text.length - 1) split_text.splice(line - 1, 0, text);
else split_text.push(text);
ta.textContent = split_text.join("\n");
}
addLine("This is my new text here!", 3);
addLine("This is another example!", 7);
addLine("And one more!", 2);
function addLine(text, line) {
let ta = document.querySelector("textarea"),
split_text = ta.textContent.split(/\n/gmi);
if (line <= split_text.length - 1) split_text.splice(line - 1, 0, text);
else split_text.push(text);
ta.textContent = split_text.join("\n");
}
addLine("This is my new text here!", 3);
addLine("This is another example!", 7);
addLine("And one more!", 2);
textarea {
width: 300px;
height: 300px;
}
<textarea>
line 1 text
line 2 text
line 3 text
line 4 text
line 5 text</textarea>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments