[英]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.