开发者

Javascript regex with quotes

I need a 开发者_运维技巧way to replace all appearances of <br class=""> with just <br>

I'm a complete novice with regex, but I tried:

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. 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;


One way is with the following

var s = '<br class="">';
var n = s.replace(/(.*)(\s.*)(>)/,"$1$3");
console.log(n)


\s matches exactly one whitespace character. You probably want \s*, which will match any number (including zero) of whitespace characters, and \s+, which will match at least one.

str = str.replace(/'<br\s+class=\"\"\s*>/g, "<br>");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜