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>
Updated ansWer
let str = firstTextArea.value.replace(/[(?:\r\n|\r|\n),]+/g, '<br>');
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.