search

Home  >  Q&A  >  body text

Use regular expressions to match id values

<p>I want to find all child nodes of the <code>g</code> node whose value is <code>id</code> and the attribute consists of: </p> <pre class="brush:php;toolbar:false;">a[number]-[one or more characters] // example: // - id="a1-a" // - id="a1-b" // - id="a1-abcd" // - id="a10-f" // - id="a0-z" // - id="b1-a" // Illegal // - id="a1-2" // Illegal</pre> <p>So I tried: </p> <pre class="lang-js prettyprint-override"><code>const items = gElement.querySelectorAll(`[id^='a[0-9] -[a-zA-Z] ']`) </code></pre> <p>However, it doesn't work. </p>
P粉757556355P粉757556355444 days ago567

reply all(1)I'll reply

  • P粉237647645

    P粉2376476452023-08-31 10:23:22

    In your query selector, you are using a pattern ([0-9] ) that is not interpreted as a regular expression. Create a regular expression object from a string using the RegExp constructor:

    const regex = new RegExp('^a[0-9]+-[a-zA-Z]+$');
    const parentElement = document.querySelector('#parent-element');
    const items = parentElement.querySelectorAll(`[id]`);
    const children = Array.from(items).filter(item => regex.test(item.id));
    
    console.log(children); 
    <div id="parent-element">
      <p id="a1-a">Child 1</p>
      <p id="a1-b">Child 2</p>
      <p id="INVALID-1">Child 3</p>
      <p id="a10-f">Child 4</p>
      <p id="INVALID-2">Child 5</p>
      <p id="b1-a">Child 6</p>
      <p id="a1-2">Child 7</p>
    </div>

    reply
    0
  • Cancelreply