正则表达式为html属性加引号 [英] Regex to put quotes for html attributes

查看:373
本文介绍了正则表达式为html属性加引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html标记中有这样的场景



,如果这些属性不是由单引号或双引号包围的话,那么我想为它添加双引号

如何编写正则表达式? 解决方案

这个正则表达式与元素中可能存在标签的次数一样多,只要文本相当正常,并且不包含大量可能给出误报的特殊字符,就应该有效。

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



<正则表达式:开放标签(< ),后跟一个或多个不结束标签( [^>] + ),然后是等于( = )全部作为第一组捕获c>(...)),然后是第二组((...)),不会捕获单引号或双引号或空格( [^'\s] ),然后不是空格或关闭标记( [^ \s>] )一次或多次( + ),然后将其替换为第一个捕获的组( $ 1 ),然后用单引号('$ 2'

例如循环: 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);

但这是一个糟糕的最好使用HTML解析器来解析,然后重新格式化HTML,这样可以确保格式正确的HTML格式正则表达式只能确保格式良好的HTML,如果输入正好与预计。

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?

解决方案

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.

这篇关于正则表达式为html属性加引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆