Find paragraphs in text.
P粉288069045
P粉288069045 2023-07-28 13:08:03
0
1
605
<p>I'm trying to implement an "Edit" button using JavaScript on a Django website. Although I am very new to JavaScript. </p><p>Splitting text into paragraphs is very easy in Django, you just need to code {{ text|linebreaks }} like this and Django will add the <p> tag dynamically. To make the transition smooth (after sending the fetch request and receiving the response), I need to create a function that loops through the edited text and generates the corresponding <p> tags. </p><p>However, I don’t even know where to start. How to find exactly where each paragraph ends using JavaScript? </p><p><br /></p>
P粉288069045
P粉288069045

reply all(1)
P粉239164234

You can use <br> to split text into paragraphs based on line breaks. Suppose that after getting the edited text from Django, you store it in a variable called editedText. In order to generate <br> tags for each paragraph, you can follow these steps:

Use the split() function to split the text into an array of paragraphs. Generate new formatted text by looping through an array of paragraphs and concatenating them using <br> tags.

<div id="edited-text">{{ edited_text }}</div>
<button onclick="formatEditedText()">Edit</button>

<script>
function formatEditedText() {
  const editedTextDiv = document.getElementById('edited-text');
  const editedText = editedTextDiv.innerHTML;

  const paragraphs = editedText.split('<br>');

  let formattedText = '';
  for (let i = 0; i < paragraphs.length; i++) {
    formattedText += `<p>${paragraphs[i]}</p>`;
  }

  editedTextDiv.innerHTML = formattedText;
}
</script>

Should be useful

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template