[英]javascript regex for xml/html attributes
I cant seem to be able to build a good regex expression (in javascript) that extracts each attribute from an xml node. 我似乎无法建立良好的regex表达式(使用javascript),该表达式从xml节点提取每个属性。 For example, 例如,
<Node attribute="one" attribute2="two" n="nth"></node>
I need an express to give me an array of 我需要快递给我一些
['attribute="one"', 'attribute2="two"' ,'n="nth"']
... Any help would be appreciated. ... 任何帮助,将不胜感激。 Thank you 谢谢
In case you missed Kerrek's comment: 如果您错过了Kerrek的评论:
And the link: RegEx match open tags except XHTML self-contained tags 以及链接: RegEx匹配除XHTML自包含标签之外的其他打开标签
You can get the attributes of a node by iterating over its attributes property: 您可以通过迭代节点的attribute属性来获取节点的属性:
function getAttributes(el) {
var r = [];
var a, atts = el.attributes;
for (var i=0, iLen=atts.length; i<iLen; i++) {
a = atts[i];
r.push(a.name + ': ' + a.value);
}
alert(r.join('\n'));
}
Of course you probably want to do somethig other than just put them in an alert. 当然,除了将它们置于警报状态之外,您可能还想做其他事情。
Here is an article on MDN that includes links to relevant standards: 这是一篇有关MDN的文章,其中包含相关标准的链接:
https://developer.mozilla.org/En/DOM/Node.attributes https://developer.mozilla.org/En/DOM/Node.attributes
try this~ 试试这个〜
<script type="text/javascript">
var myregexp = /<node((\s+\w+=\"[^\"]+\")+)><\/node>/im;
var match = myregexp.exec("<Node attribute=\"one\" attribute2=\"two\" n=\"nth\"></node>");
if (match != null) {
result = match[1].trim();
var arrayAttrs = result.split(/\s+/);
alert(arrayAttrs);}
</script>
The regex is /\\w+=".+"/g
(note the g
of global ). 正则表达式为/ /\\w+=".+"/g
g
".+"/ g
(注意global的g
)。
You might try it right now on your firebug / chrome console by doing: 您可以立即在Firebug / Chrome控制台上尝试执行以下操作:
var matches = '<Node attribute="one" attribute2="two" n="nth"></node>'.match(/\w+="\w+"/g)
I think you could get it using the following. 我认为您可以使用以下方法获得它。 You would want the second and third matching group. 您需要第二和第三个匹配组。
<[\w\d\-_]+\s+(([\w\d\-_]+)="(.*?)")*>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.