0

For Example:
"first line<br><br>Second line" should be replaced with "first line<br>Second line"
"first line<br><br><br>Second line" should be replaced with "first line<br><br>Second line" and so on...

What I am trying to do is replace all newline characters in a string recieved from textarea with <br> in a string using the regex: "str.replace(/(?:\r\n|\r|\n)/g, '<br>')" but this puts one extra <br> tag because when someone is typing in the textarea they press enter twice instead of once for a newline.

Code:

<textarea style="width:200px;height:200px" id="first"></textarea>
<textarea style="width:200px;height:200px;" id="second"></textarea>
<button id="submit">submit</button>

<script type="text/javascript">
    const firstTextArea = document.querySelector('#first');
    const secondTextArea = document.querySelector('#second');
    const submitBtn = document.querySelector('#submit')
    submitBtn.addEventListener('click' , function(){
        let str = firstTextArea.value.replace(/(?:\r\n|\r|\n)/g, '<br>');
        secondTextArea.value = str;
    })

</script>

OUTPUT: enter image description here

AfaqQazi
  • 21
  • 5
  • 6
    Regex is the wrong tool for this. – Andy Sep 23 '22 at 10:52
  • Use a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) and manipulate it using standard DOM methods. – evolutionxbox Sep 23 '22 at 10:55
  • 1
    Does this answer your question? [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg) – Michał Turczyn Sep 23 '22 at 10:56

2 Answers2

1

Updated ansWer

let str = firstTextArea.value.replace(/[(?:\r\n|\r|\n),]+/g, '<br>');

https://jsfiddle.net/FireAnt121/ts1qyLm9/3/

FireAnt121
  • 21
  • 5
1

You can do something like this:

 /** split the string by the line breaks. Line breaks are returned as empty strings */
 const brokenString = firstTextArea.value.split(/(?:\r\n|\r|\n)/g);
  
 /** remove the empty strings. Then join the other parts back by '<br>' */
 const rejoinedString = brokenString.filter(s => s !== '').join('<br>');
  
 secondTextArea.value = rejoinedString;

Here is an example:

Input:

first
second line

third line with spaces



fourth line with spaces

Output

first<br>second line<br>third line with spaces<br>fourth line with spaces

I have created this Pen. You can try it out: https://codepen.io/bisdas/pen/gOzGXMJ

Bishnu Das
  • 462
  • 1
  • 3
  • 9