我有这个结果字符串:
<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, "");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句