skip to Main Content

I’m trying to implement an ‘edit’ button on a django website using javascript. I’m very new to javascript though.

In django it’s pretty easy to split the text into paragraphs, you just code it like this {{ text|linebreaks }} and django adds <p> tags dynamically. To make the transition smooth (after sending fetch request and receiving response) with javascript I need to create a function that loops through the edited text and generates <p> tags as well.

However I dont’ even know where to start. How exactly do you find where each paragraph ends using javascript?

2

Answers


  1. From the docs, the definition is (although not clear at first as in this definition) that new line gets a <br> whereas double gets a <p>

    var text = `hello world
    
    this is second paragraph
    however it has a line break.`;
    
    var new_text = text.split("nn").map(line => `<p>${line}</p>`).join("").replace("n", "<br>");
    
    
    document.write (new_text)
    console.log(new_text);
    Login or Signup to reply.
  2. you can split the text into paragraphs based on line breaks by using <br>. Let’s assume that after fetching the edited text from Django, you have it stored in a variable called editedText. To generate <br> tags for each paragraph, you can follow these steps:

    Split the text into an array of paragraphs using the split() function.
    Loop through the array of paragraphs and join them using <br> tags to generate the new formatted text.

    <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>
    

    Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search