【问题标题】:javascript getattribute method with regex带有正则表达式的javascript getattribute方法
【发布时间】:2020-08-20 04:29:49
【问题描述】:
<div id="foo" platform="bar" table-index="1">
  hello!
</div>

如果我使用 getAttribute 方法并获取值,它会是这样的

var ele = document.querySelector("#foo").getAttribute("platform")

我可以通过ele变量得到“bar”。

但我想使用带有正则表达式的 getAttribute。

var ele = document.querySelector("#foo").getAttribute(`regex contains just "index"`)

单词“table-index”以索引结尾。所以我想找到属性并获得 1(表索引值)只需使用“索引”和正则表达式。

我不知道如何在 attiributeName 中使用正则表达式。

【问题讨论】:

    标签: javascript regex getattribute


    【解决方案1】:

    getAttribute 不能以这种方式使用——它接受一个字符串作为参数,而不是一个正则表达式。但是,您可以实现一种类似的方法。下面的方法通过使用元素的 [attributes] 属性,然后遍历它们,搜索与正则表达式匹配的元素,然后返回该值。

    请注意,此特定实现天真地假设您使用的正则表达式将仅匹配元素上的单个属性并返回它遇到的第一个匹配项 - 但是,您可以更聪明并编写更强大的返回匹配的属性/值对数组。

    function getAttributeByRegex(element, regex) {
      const attributes = element.attributes;
      for (let i = attributes.length - 1; i >= 0; i--) {
        const attr = attributes[i];
        if (regex.test(attr.name)) {
          return attr.value;
        }
        return undefined;
      }  
    }
    
    const value = getAttributeByRegex(
      document.querySelector('#foo'),
      /-index/
    );
    
    console.log(value);
    <div id="foo" platform="bar" table-index="1">
      hello!
    </div>

    【讨论】:

    • 非常感谢!您的示例完美运行,并帮助我制作了 js 功能。
    • 很高兴它有帮助!编码愉快!
    【解决方案2】:

    您必须遍历属性以找到名称与您的 RegExp 匹配的属性。

    function regexMatch(element, regex) {
      let match = [...element.attributes].find(i => regex.test(i.name));
      if (!match) return undefined;
      return match.value;
    }
    
    let ele = regexMatch(document.querySelector("#foo"), /index/g);
    console.log(ele);
    <div id="foo" platform="bar" table-index="1">
      hello!
    </div>

    【讨论】:

      【解决方案3】:

      const match = findAttributeMatch("foo", "index");
      console.log(document.querySelector('#foo').getAttribute(match));
      
      function findAttributeMatch(id, attribute) {
        const regex = RegExp(`(${attribute})`, 'gm');
        const element = document.querySelector(`#${id}`);
      
        const a = [...element.attributes].find(node => regex.test(node.name));
        return a && a["name"];
      }
      <!DOCTYPE html>
      <div id="foo" platform="bar" table-index="1">
        hello!
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-07
        • 2015-09-24
        • 2012-02-13
        • 1970-01-01
        相关资源
        最近更新 更多