简体   繁体   中英

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:

  • match1 <input type="text" value="#tag3" notified="true" class="label-primary hashtag">
  • match2 #tag
  • match3 true

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

.classname是一个类选择器, [propertyname=value]是一个值选择器,因此您可以执行以下操作:

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM