Carlos
Carlos

Reputation: 13

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:

Upvotes: 1

Views: 3513

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 241198

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.

  • (?=[^>]*value=\"([^"]+)\") - Positive lookahead with a capturing group to match the value attribute's value after zero or more non-> characters.

  • (?=[^>]*?notified=\"([^"]+)\") - Positive lookahead with a capturing group to match the notified attribute's value after zero or more non-> characters.

Capturing groups:

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

Group 2 - #tag3

Group 3 - true

Upvotes: 3

Carlos
Carlos

Reputation: 13

Josh solved my question, and this is why:

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

string.replace(reg, '[$2]($3)');

// prints [#tag3](true)

Thanks mate!

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 77045

.classname is a class selector, [propertyname=value] is a value selector, so you can do something like:

document.querySelectorAll('input.hashtag[notified=true]')

Upvotes: 0

Related Questions