繁体   English   中英

需要 Javascript 正则表达式删除一个“<br> “标签来自任意数量的连续”<br> " 字符串中的标签

[英]Need Javascript Regex to Remove one "<br>" tag from any number of consecutive "<br>" tags in a string

例如:
"first line<br><br>Second line"应替换为"first line<br>Second line"
"first line<br><br><br>Second line"应替换为"first line<br><br>Second line" ,依此类推...

我想要做的是使用正则表达式用字符串中的<br>替换从 textarea 接收的字符串中的所有换行符: "str.replace(/(?:\r\n|\r|\n)/g, '<br>')"但这会添加一个额外的<br>标签,因为当有人在 textarea 中输入时,他们按两次 Enter 键而不是一次换行符。

代码:

<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: 在此处输入图像描述

更新的答案

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

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

你可以这样做:

 /** 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;

这是一个例子:

输入:

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

我创造了这支笔。 你可以试试看: https://codepen.io/bisdas/pen/gOzGXMJ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM