Nika Nika - 10 months ago 48
Javascript Question

Javascript Regex: How to extract html tag values in group?


I'm new to regex (still practicing) and I'm trying to extract

script src
link href
values from tags (for education purposes).

Given following html

<!-- hello -->
<script src="1.js"></script>
<script src="2.js"></script>
<link rel="stylesheet" href="3.css"/>
<!-- world -->

I'd want to get

array of:

I've tried

This is the regex I've did so far, but meh.

/(?:<!-- hello -->\s*?)([\s\S]*?)(?:\s?<!-- world -->)/gmi

Of course, I have to replace
with something better but I've tried a lot of combinations and none of them worked.



Only scripts between
<!-- xxx --><!-- xxx-->
tags should be matched.

Following should not match:

<!-- foo-->
<script src="4.js"></script>
<script src="5.js"></script>
<link rel="stylesheet" href="6.css"/>
<!-- bar-->

Answer Source

use the regex

<!-- hello -->([\S\s]+)<!-- world -->

to extract the valid string in the first group see the regex demo

then you can use the regex

<(?:script src.*|link.*href)="(\w+\.\w+)

all matches would be in group 1

see the regex demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download