[英]How to remove <br> at the beginning and at the end of a string in javascript using regex?
I have this resulted string: 我有这个结果字符串:
<br><br><br>This is an example!<br>Test1!<br>Test2!<br><br>
Attempted code: 试图代码:
var string = "<br><br><br>This is an example!<br>Test1<br>Test2<br><br>";
var remove = string.replace(/^(<br>)+/g, "");
console.log(remove);
But these codes is removing only the first br's in a string when I add $
at the end of (<br>)
, so my code will fail. 但是当我在(<br>)
的末尾添加$
时,这些代码只删除字符串中的第一个br,所以我的代码将失败。 My question is how to remove the <br>
at the beginning and at the end of a string? 我的问题是如何在字符串的开头和结尾删除<br>
?
Expected output: when used console.log 预期输出:使用console.log时
This is an example!<br>Test1!<br>Test2!
You're close, what you're looking for is an alternation : |
你很亲密,你正在寻找的是一个变化 : |
var remove = string.replace(/^(<br>)+|(<br>)+$/g, "");
That will match ^(<br>)+
or (<br>)+$
, and since your regex is global, both occurences will be replaced. 这将匹配^(<br>)+
或 (<br>)+$
,并且因为你的正则表达式是全局的,所以两个出现都将被替换。
Live Example: 实例:
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>
I would also replace the capture groups with non-capturing groups ( (?:...)
), but that's probably just me being OTT: 我也会用非捕获组替换捕获组( (?:...)
),但这可能只是我的OTT:
var remove = string.replace(/^(?:<br>)+|(?:<br>)+$/g, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.