开发者

Javascript regex with quotes

开发者 https://www.devze.com 2023-03-24 19:48 出处:网络
I need a 开发者_运维技巧way to replace all appearances of <br class=\"\">with just <br>

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

精彩评论

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