[英]Need Javascript Regex to Remove one "<br>" tag from any number of consecutive "<br>" tags in a string
For Example:例如:
"first line<br><br>Second line"
should be replaced with "first line<br>Second line"
"first line<br><br>Second line"
应替换为"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... "first line<br><br><br>Second line"
应替换为"first line<br><br>Second line"
,依此类推...
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.我想要做的是使用正则表达式用字符串中的
<br>
替换从 textarea 接收的字符串中的所有换行符: "str.replace(/(?:\r\n|\r|\n)/g, '<br>')"
但这会添加一个额外的<br>
标签,因为当有人在 textarea 中输入时,他们按两次 Enter 键而不是一次换行符。
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>');
https://jsfiddle.net/FireAnt121/ts1qyLm9/3/ https://jsfiddle.net/FireAnt121/ts1qyLm9/3/
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 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
你可以试试看: https://codepen.io/bisdas/pen/gOzGXMJ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.