如何使用JavaScript正则表达式获取html标签属性值? [英] How to get html tag attribute values using JavaScript Regular Expressions?

查看:1290
本文介绍了如何使用JavaScript正则表达式获取html标签属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在字符串中包含此HTML:

Suppose I have this HTML in a string:

<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">

我有这个正则表达式,以获取内容中的值属性:

And I have this regular expression, to get the values inside the content attributes:

/<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig

如何在JavaScript中获取所有三个内容值?

How do I, in JavaScript, get all three content values?

我尝试过:

var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;
var match = setCookieMetaRegExp.exec(htmlstring);

匹配不包含值我需要。帮助?

but match doesn't contain the values I need. Help?

注意:正则表达式已经正确(见这里)。我只需要将它与字符串匹配。
注意:我正在使用NodeJS

Note: the regular expression is already correct (see here). I just need to match it to the string. Note: I'm using NodeJS

推荐答案

你真是太近了!现在需要做的只是一个简单的循环:

You were so close! All that needs to be done now is a simple loop:

var htmlString = '<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">\n';

var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;

var matches = [];
while (setCookieMetaRegExp.exec(htmlString)) {
  matches.push(RegExp.$1);
}

//contains all cookie values
console.log(matches);

JSBIN: http://jsbin.com/OpepUjeW/1/edit?js,console

这篇关于如何使用JavaScript正则表达式获取html标签属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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