![](/img/trans.png)
[英]Regex to remove all <br /> tags from beginning and end of a string in javascript
[英]How to remove <br> at the beginning and at the end of a string in javascript using regex?
我有這個結果字符串:
<br><br><br>This is an example!<br>Test1!<br>Test2!<br><br>
試圖代碼:
var string = "<br><br><br>This is an example!<br>Test1<br>Test2<br><br>";
var remove = string.replace(/^(<br>)+/g, "");
console.log(remove);
但是當我在(<br>)
的末尾添加$
時,這些代碼只刪除字符串中的第一個br,所以我的代碼將失敗。 我的問題是如何在字符串的開頭和結尾刪除<br>
?
預期輸出:使用console.log時
This is an example!<br>Test1!<br>Test2!
你很親密,你正在尋找的是一個變化 : |
var remove = string.replace(/^(<br>)+|(<br>)+$/g, "");
這將匹配^(<br>)+
或 (<br>)+$
,並且因為你的正則表達式是全局的,所以兩個出現都將被替換。
實例:
var string = "<br><br><br>This is an example!<br>Test1<br>Test2<br><br>"; var remove = string.replace(/^(<br>)+|(<br>)+$/g, ""); snippet.log(remove);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
我也會用非捕獲組替換捕獲組( (?:...)
),但這可能只是我的OTT:
var remove = string.replace(/^(?:<br>)+|(?:<br>)+$/g, "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.