I’m trying to get the number of lines that a textarea has for a line counter (for a text editor), but if there is an emtpy line in the textarea, there are two new lines added. Here is the output:
["// Hello World!","","","The line above was empty","","","Same here!","The line on the bottom of this one is empty!","",""]
My code:
function getLines() { var textValue = document.querySelector('#editor').value; var lines = textValue.split("n"); console.log(lines); }
At someone’s request, here is the HTML:
<div id="visible" contenteditable="true" onkeyup="updateLineCount()">// Hello World!</div> <textarea id="code-editor">
Basically I plan on adding syntax highlighting, so the div is content editable, and the JS sends the stuff in the div to the textarea, just to calculate the lines of code. Here is the JS that does this:
textarea.value = document.querySelector("#code-editor").innerText;
Advertisement
Answer
The issue you are running into has to do with pulling the innerText
value of your contenteditable div and placing it into a <textarea>
. This is where the extra newline characters n
are coming from.
Unless you are required to use the <textarea>
I would just get the line count from the contenteditable div directly. The only weird quirk here is that there is an extra newline character n
added to the very end of the innerText
, but this can just be removed using .split(0, -1)
.
const updateLineCount = () => { document.querySelector(".lines").innerHTML = [...Array(document.querySelector("#code-editor").innerText.slice(0, -1).split("n").length).keys()].map(v => v+1).join("<br>") } document.querySelector("#code-editor").addEventListener("keyup", updateLineCount)
.code { padding: .2em .4em; border: 1px solid #CCC; box-sizing: border-box; display: inline-block; } .lines { color: #555; font-family: monospace; width: 2em; vertical-align: top; border-right: 1px solid #CCC; display: inline-block; } #code-editor { font-family: monospace; width: 40em; vertical-align: top; display: inline-block; } #code-editor:focus { outline: none; }
<div class="code"> <div class="lines">1</div> <div id="code-editor" contenteditable="true">// Hello World!</div> </div>