Use regular expressions to match id values
P粉757556355
2023-08-30 16:13:18
<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>
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: