Regex to put quotes for html attributes

╄→尐↘猪︶ㄣ 提交于 2019-12-23 03:51:28

问题


I have a scenario like this

in html tags, if the attributes is not surrounded either by single or double quotes.. i want to put double quotes for that

how to write regex for that?


回答1:


If you repeat this regex as many times as there might be tags in an element, that should work so long as the text is fairly normal and not containing lots of special characters that might give false positives.

"<a href=www.google.com title = link >".replace(/(<[^>]+?=)([^"'\s][^\s>]+)/g,"$1'$2'")

Regex says: open tag (<) followed by one or more not close tags ([^>]+) ungreedily (?) followed by equals (=) all captured as the first group ((...)) and followed by second group ((...)) capturing not single or double quote or space ([^"'\s]) followed by not space or close tag ([^\s>]) one or more times (+) and then replace that with first captured group ($1) followed by second captured group in single quotes ('$2')

For example with looping:

html = "<a href=www.google.com another=something title = link >";
newhtml = null;
while(html != newhtml){
   if(newhtml)
        html = newhtml;
   var newhtml = html.replace(/(<[^>]+?=)([^"'\s][^\s>]+)/,"$1'$2'");
}
alert(html);

But this is a bad way to go about your problem. It is better to use an HTML parser to parse, then re-format the HTML as you want it. That would ensure well formatted HTML wheras regular expressions could only ensure well formatted HTML if the input is exactly as expected.




回答2:


Very helpful! I made a slight change to allow it to match attributes with a single character value: /(<[^>]+?=)([^"'\s>][^\s>]*)/g (changed one or more + to zero or more * and added > to the first match in second group).



来源:https://stackoverflow.com/questions/6622483/regex-to-put-quotes-for-html-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!