[英]Javascript regex with quotes
I need a way to replace all appearances of <br class="">
with just <br>
我需要一种仅用
<br>
替换<br class="">
所有外观的方法
I'm a complete novice with regex, but I tried: 我是regex的新手,但我尝试过:
str = str.replace(/<br\sclass=\"\"\s>/g, "<br>");
and it didn't work. 而且没有用
What's a proper regex to do this? 什么是合适的正则表达式来做到这一点?
I would not use a regex to do this, but rather actually parse the html and remove the classes. 我不会使用正则表达式来执行此操作,而是实际上解析html并删除类。 This is untested, but probably works.
这未经测试,但可能有效。
// Dummy <div> to hold the HTML string contents
var d = document.createElement("div");
d.innerHTML = yourHTMLString;
// Find all the <br> tags inside the dummy <div>
var brs = d.getElementsByTagName("br");
// Loop over the <br> tags and remove the class
for (var i=0; i<brs.length; i++) {
if (brs[i].hasAttribute("class")) {
brs[i].removeAttribute("class");
}
}
// Return it to a string
var yourNewHTMLString = d.innerHTML;
\\s
matches exactly one whitespace character. \\s
恰好匹配一个空格字符。 You probably want \\s*
, which will match any number (including zero) of whitespace characters, and \\s+
, which will match at least one. 您可能想要
\\s*
,它将匹配任何数量(包括零个)的空格字符,以及\\s+
,它将匹配至少一个字符。
str = str.replace(/'<br\s+class=\"\"\s*>/g, "<br>");
One way is with the following 一种方法是以下
var s = '<br class="">';
var n = s.replace(/(.*)(\s.*)(>)/,"$1$3");
console.log(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.