正则表达式提取div的所有属性

时间:2011-07-18 11:33:59

标签: javascript regex

我需要提取某些标签的所有属性。所以我想为此进行正则表达式。例如<sometag attr1="val1" attr2="val2" ></sometag>。我希望属性和值作为名称值对。

任何帮助表示赞赏

感谢

8 个答案:

答案 0 :(得分:3)

var s = '<sometag attr1="val1" attr2="val2" ></sometag>';
var reg = /\s(\w+?)="(.+?)"/g;
while( true ) {
    var res = reg.exec( s );
    if( res !== null ) {
        alert( 'name = '+res[1] );
        alert( 'value = '+res[2] );
    } else {
        break;
    }
}

答案 1 :(得分:2)

preg_match_all( '/\s(\w+?)="(.+?)"/', '<sometag attr1="val1" attr2="val2" ></sometag>', $matches );
for( $i = 0; $i < count( $matches[1] ); ++$i ) {
    $name = $matches[1][$i];
    $value = $matches[2][$i];
    echo 'name'.$i.' = "'.$name.'", value'.$i.' = "'.$value.'", ';
}

结果:

name0 = "attr1", value0 = "val1", name1 = "attr2", value1 = "val2",  

当然你需要调整它以满足你的需要并处理坏的HTML。

答案 2 :(得分:1)

您可以使用[jquery] [1]获取元素的所有属性

$('sometag').getAttributes();

http://plugins.jquery.com/project/getAttributes

答案 3 :(得分:1)

不需要正则表达式。更容易,使用Element.attributes()

var attributes = element.attributes();

“返回一个数组(NamedNodeMap),其中包含为相关元素定义的所有属性,包括自定义属性。”请参阅链接以获取有关如何访问每个属性及其值的示例。

答案 4 :(得分:1)

使用正则表达式无法在本机JavaScript中执行此操作。使用本机JavaScript,您有几个基本选项。您可以枚举所有节点的属性并智能地过滤以获得您想要的内容,例如:

window.extractAttributes = function(node) {
    var attribString = "";
    var template = document.createElement(node.tagName);
    template.innerHTML = node.innerHTML;
    for (var key in node) {
        if (typeof node[key] == "string" && node[key] != "" && ! template[key]) {
            if (attribString.length > 0) {
                attribString += ", ";
            }
            attribString += key + "=" + node[key];
        }
    }

    return attribString;
};

或者您可以使用Element.attributes来迭代声明的属性列表(请注意,这可能无法检测在运行时动态添加的非标准属性值),例如:

window.extractAttributesAlternate = function(node) {
    var attribString = "";
    for (var index = 0; index < node.attributes.length; index++) {
        if (attribString.length > 0) {
            attribString += ", ";
        }
        attribString += node.attributes[index].name+ "=" + node.attributes[index].nodeValue;
    }

    return attribString;
}; 

请注意,第一种方法可能无法获取已在页面标记中定义的自定义属性,并且第二种方法可能无法获取已由页面上的JavaScript动态定义的自定义属性。

它为我们提供了选项3.您可以双向枚举属性,然后合并结果。这样做的好处是能够可靠地获取任何自定义属性,无论它们何时/如何添加到元素中。

以下是所有3个选项的示例:http://jsfiddle.net/cgj5G/3/

答案 5 :(得分:0)

您可以使用XML解析器,因为提供的输入是格式良好的XML。

答案 6 :(得分:0)

使用正则表达式! Javacript的DOM已经拥有您需要的所有信息,可以轻松访问。

列出DOM元素的所有属性:

var element = document.getElementById('myElementName');
var attributes = element.attributes;
for(var attr=0; attr<attributes.length; attr++) {
    alert(attributes[attr].name+" = "+attributes[attr].nodeValue);
}

(在上面的代码中测试了FF5,IE8,Opera11.5,Chrome12:适用于所有这些代码,即使使用非标准属性)

答案 7 :(得分:0)

给定包含其开始和结束标记的单个元素的文本(等同于元素的outerHTML),以下函数将返回包含所有属性name = value对的对象。每个属性值可以是单引号,双引号或不引用。属性值是可选的,如果不存在则将采用属性的名称。

function getElemAttributes(elemText) {
    // Regex to pick out start tag from start of element's HTML.
    var re_start_tag = /^<\w+\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[\w\-.:]+))?)*\s*\/?>/;
    var start_tag = elemText.match(re_start_tag);
    start_tag = start_tag ? start_tag[0] : '';
    // Regex to pick out attribute name and (optional) value from start tag.
    var re_attribs = /\s+([\w\-.:]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([\w\-.:]+)))?/g;
    var attribs = {};   // Store attribute name=value pairs in object.
    var match = re_attribs.exec(start_tag);
    while (match != null) {
        var attrib = match[1];  // Attribute name in $1.
        var value  = match[1];  // Assume no value specified.
        if (match[2]) { // If match[2] is set, then attribute has a value.
            value = match[3] ? match[3] : // Attribute value is in $3, $4 or $5.
                    match[4] ? match[4] : match[5];
        }
        attribs[attrib] = value;
        match = re_attribs.exec(start_tag);
    }
    return attribs;
}

鉴于此输入:

<sometag attr1="val1" attr2='val2' attr3=val3 attr4 >TEST</sometag>

这是输出:

attrib = {
    attr1: "val1",
    attr2: "val2",
    attr3: "val3",
    attr4: "attr4"
    };