![](/img/trans.png)
[英]How can I insert or remove a tab before / after every new line in a string with Javascript?
[英]How to use JavaScript to loop through a long string to insert a new string after every match
我有一个包含表示XML文档的长字符串的变量。 在该字符串中,我需要搜索每个自动关闭标记并扩展为两个匹配的开始/结束标记。 我真的不确定如何解决这个问题,并希望得到你的建议。 在这一点上,我所知道的是如何通过正则表达式来匹配自动关闭标签: [^<]+?/>
这是我想要完成的一个简短示例:
原始字符串:
<outer-tag>
<inner-tag-1>
<SELF-CLOSING-TAG-1 foo="bar"/>
<SELF-CLOSING-TAG-2/>
</inner-tag-1>
<inner-tag-2>
<SELF-CLOSING-TAG-3 attr="value"/>
</inner-tag-2>
</outer-tag>
修改过的字符串:
<outer-tag>
<inner-tag-1>
<SELF-CLOSING-TAG-1 foo="bar"></SELF-CLOSING-TAG-1>
<SELF-CLOSING-TAG-2></SELF-CLOSING-TAG-2>
</inner-tag-1>
<inner-tag-2>
<SELF-CLOSING-TAG-3 attr="value"></SELF-CLOSING-TAG-3>
</inner-tag-2>
</outer-tag>
尝试
the_string.replace(/< *(\w+)([^<\/>]*)\/>/g, "<$1$2></$1>")
说明:
< opening tag
' *' ignore whitespace
$1 (\w+) tag name (remember at $1)
$2 ([^<\/>]*) attributes (remember at $2)
\/> close tag
我已经使用w3规范来创建一个正则表达式,正确解析格式良好的XML中的标签。
首先,选择定义起始标签的字符(按规格)。 然后,匹配剩余的字符,不包括可能尾随间隔和/>
。 全局替换匹配的子串
"<" + starttag + remaining + "></" + starttag + ">"
。 见下文:
//According to the W3 spec:
var pattern = /<([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][-.0-9\xB7\u0300-\u036F\u0203F-\u2040]*)([^>]*?)\s*?\/>/g;
string.replace(pattern, '<$1$2></$1>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.