How can I split an input text by line in javascript?

Viewed 22

I want to copy a long Python code (100 lines of code) into the input in the HTML. When I do that it does not show the new line, or I don't know but when I split by the new line in the javascript, console.log(lines) only shows an array with one element.

How can I fix this issue? Every new line should be a new element of the list.

['class Person:   def __init__(self, name, age):    … Person("John", 36)  print(p1.name) print(p1.age)']

function show() {
  //alert(getClassName('Class Person(Dalai):'))
  //alert(getMethodParameters('def sing(self, song, hel):'))
  //alert(getMethodName('def sing(self, song, hel):'))
  text = getText()
  var lines = text.split(/\n/)
  console.log(lines);
}

function getText() {
  var text = document.getElementById('text')
  return (text.value)
}
<input type="text" name="" id="text" placeholder="Copy your python code">
<button onclick="show()">Submit</button>

1 Answers

Instead of using JavaScript to add new lines, use the <textarea> element to keeps the new lines and indentation:

function show() {
  document.getElementById("output").value = document.getElementById("text").value;
}
<textarea cols="40" rows="8" name="" id="text" placeholder="Copy your python code"></textarea>
<button onclick="show()">Submit</button>
<br>
<textarea cols="40" rows="8" name="" id="output" placeholder="You see the output keeps new lines and indentation" readonly></textarea>

Related