[英]Regex to remove all <br /> tags from beginning and end of a string in javascript
[英]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>
更新的答案
let str = firstTextArea.value.replace(/[(?:\r\n|\r|\n),]+/g, '<br>');
你可以這樣做:
/** 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.