javascriptregexmatch

JavaScript regex: Find a tag and get some attribute values


i need to capture a html tag by class and some attribute value.

I've resolved the first part, capturing the tag by class (the querySelector should be something like: 'input.hashtag'):

<input type="text" value="#tag3" notified="true" class="label-primary hashtag">

So, im using this regex:

/(?=<input[^>]+(?=[\s+class=\"]hashtag[\s+\"]).+)([^>]+>)/g

You can checkout the test here https://regex101.com/r/zY4sH9/6

What i need is to capture also the attribute values: value and nofified, to finally get:


Solution

  • You said that you're already using the .querySelector() method, therefore I would suggest avoiding regular expressions and using the native DOM methods.

    var element = document.querySelector('input.hashtag'),
        value = element.value,
        notified = element.getAttribute('notified');
    

    Similarly, if you want to select an input element that has a .hashtag class and value/notified attribute, then you could simply use two attribute selectors input.hashtag[value][notified]:

    var element = document.querySelector('input.hashtag[value][notified]'),
        value = element.value,
        notified = element.getAttribute('notified');
    

    However, if you need to use regular expressions, the following would capture the value and notified attribute's value regardless of order (since positive lookaheads are being used):

    /(<input(?=[^>]*[\s+class=\"]hashtag[\s+\"])(?=[^>]*value=\"([^"]+)\")(?=[^>]*?notified=\"([^"]+)\")[^>]*\>)/
    

    Updated Example

    I just built off of your existing expression, so I don't need to explain the first part.

    Capturing groups:

    Group 1 - <input type="text" value="#tag3" notified="true" class="label-primary hashtag">

    Group 2 - #tag3

    Group 3 - true