How to split bunch of sentence/line with delimiter(%) to a new line in div using jquery?

Viewed 34

How to split all the lines ending with % in textarea to display to new line in div

<textarea id='all' rows="10" cols="100">
     this is line one% this is line two% this is line three % this is line four %
 </textarea>

 <div id="split">
    this is line one
    this is line two
    this is line three
    this is line four
</div>
2 Answers

Use replaceAll() and replace % with <br/>

const all = document.getElementById("all"); 

  all.addEventListener("input", function() { 
  const btn = document.getElementById("btn"); 
  const split = document.getElementById("split"); 
  var the_paragraph = "";

    the_paragraph = the_paragraph + all.value; 
    the_paragraph = the_paragraph.replaceAll("%", "<br/>");
    split.innerHTML = the_paragraph; 
  });
  #split {
  height: 200px;
  width: 400px;
  border: 1px solid red;
  border-radius: 4px;
}

textarea {
  height: 50px;
  width: 400px;
}
<div id="split"></div>

<textarea id="all" rows="10" cols="100" placeholder="Add % for new line..."></textarea>

You can use .split("%") to split values and then use $.each to iterate through those values and append values inside your div.

Demo Code :

var values = $("#all").val().split("%") //split values
//iterate through ..them
$.each(values, function(i) {
  //apend one by one
  $("#split").append(values[i].trim() + "<br/>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='all' rows="10" cols="100">
     this is line one% this is line two% this is line three % this is line four %
 </textarea>

<div id="split">

</div>

Related