从字符串(RegExp)解析HTML元素属性

时间:2012-12-14 08:07:11

标签: javascript html regex

我只需要通过RegExp从给定的字符串中获取所有属性和文本,如果可以使用一行RegExp就可以了。我希望从字符串中获取每个attr,如果它是“或”或独立的。

  • Attr:value = "1" or value = '1' or value="1" or value='1' or value=1 or value=""
  • Attr:readonly or disabled

我试过了,但不适合我。

var s = '<option value="1" data-foo="Foo" readonly>Value 1</option>', m
m = s.match(/<option ([^>]*)>(.*)<\/option>/)
console.log(m)
// gives ["<option value="1" data-...adonly>Value 1</option>", "value="1" data-foo="Foo" readonly", "Value 1"]

非常感谢。

3 个答案:

答案 0 :(得分:0)

为什么不创建元素?

var s = '<option value="1" data-foo="Foo" readonly>Value 1</option>'​​​​​;

var test_element = document.createElement('div');
test_element.innerHTML = s;

var element = test_element.childNodes[0];
​var attributes = element.attributes;

for (var i = 0; i < attributes.length; i++) {
    var attribute = attributes[i];

    console.log(attribute.name, '=>', attribute.value);
}​

输出:

value => 1
data-foo => Foo
readonly =>  

演示:http://jsfiddle.net/mcRc4/

答案 1 :(得分:0)

以下的正则表达式我相信你想要的东西(好吧,肯定看起来很难看)但

s.match(/<option\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*>(.*)<\/option>/);

对于s = '<option value="1" data-foo="Foo" readonly>Value 1</option>',它会返回:

[
  "<option value="1" data-foo="Foo" readonly>Value 1</option>", // s itlsef
  "value", // first attr
  ""1"", // value as written in s (with double quotes)
  "data-foo", // second attr
  ""Foo"", // value as written in s (with double quotes)
  "readonly", // third attr
  undefined, // no value specified for readonly, so undefined
  "Value 1" // the option text
]

答案 2 :(得分:0)

实际上我需要这个以更简单的方式处理“选项”元素,更简单的正则表达式。如果对innerHTML = append content元素使用select,则不会附加ie的cos。附加操作在下面的链接中提到,但不适用于选项元素。而且我找到了解决这个问题的方法。如果追加内容是选项或选项而非使用handleOptionElements,如果不使用asyncInnerHTML

function append(el, child) {
    if (child.nodeType === 1 || child.nodeType === 3) {
        // Without clone, removes element if it is copied from document
        return el.appendChild(child.cloneNode(true));
    }

    content = trim(content);
    if (content.substring(0, 7) === "<option" && 
            content.substring(content.length - 7) === "option>") {
        handleOptionElements(content, el);
    } else {
        el.innerHTML = content;
    }

    return el;
}

http://james.padolsey.com/javascript/asynchronous-innerhtml/
Ways to increase performance when set big value to innerHTML

var re_standaloneAttributes = /^(select|disabl)ed$/i,
    re_optionSearch = /<option\s*([^>]*)>(.*?)<\/option>/gi,
    re_attributeSearch = /([^\s]*)=["'](.*?)["']|([\w\-]+)/g;

function handleOptionElements(content, targetElement) {
    var options = [], attributes = [],
         optionElement, optionElements = [], createOption;

    (""+ content).replace(re_optionSearch, function(src1, attr, text) {
        if (!src1) return;
        (""+ attr).replace(re_attributeSearch, function(src2, name, value) {
            if (!src2) return;
            name = name || src2;
            value = value || (value = re_standaloneAttributes.test(name) ? name : "");
            attributes.push({name: name, value: value});
        });
        options.push({text: text || "", attributes: attributes});
        // Reset attributes for each element
        attributes = [];
    });

    createOption = (function() {
        var option = document.createElement("option");
        return function() { return option.cloneNode(true) };
    })();

    forEach(options, function(option) {
        optionElement = createOption();
        // optionElement.text doesn't work on ie 7-8
        optionElement.textContent = optionElement.innerText = option.text;
        forEach(option.attributes, function(attribute) {
            optionElement.setAttribute(attribute.name, attribute.value);
        });

        if (targetElement !== undefined) {
            targetElement.appendChild(optionElement);
        } else {
            optionElements.push(optionElement);
        }
    });

    return optionElements;
}