3

I would like to regex the fullpath of the css, for example I have this:

<link rel="stylesheet" href="../assets/myCssFile.css"/>

I would like to regex: /assets/myCssFile.css

What I tried is this: /(?:href)=("|').*?([\w.]+\.(?:css))\1/gi

but this returns me this: href="../assets/myCssFile.css"

Can someone help me out with the regex.

BTW: It is an response text of an ajax request which returns me a string of the html page

5
  • 3
    You are using JS where you have so many methods to manipulate the dom elements but still want to parse href value with regex? Why? el.href should give you the necessary path. Commented Mar 20, 2018 at 15:58
  • Use href="([^"]*\.css)". Then benefit from first capturing group. Commented Mar 20, 2018 at 15:58
  • @revo Sorry but I won't run 5 km when I can take a cab. Commented Mar 20, 2018 at 16:28
  • 1
    @roundAbout to further my previous comment, it depends on whether you're getting late for an interview or are trying to lose some weight ;) Commented Mar 20, 2018 at 16:42
  • 1
    @revo the question is incorrectly tagged. While regex might be preferable option in other languages but in JS it is a big no to get the property of a element. It does not make any sense. Commented Mar 20, 2018 at 18:40

2 Answers 2

2

href=\"(.*\.css)"

This will return "../assets/myCssFile.css" in a capture group.

https://regex101.com/r/a44Axz/1

All it is doing is saying:

I am only interested in text within quotes that immediately follows an "href" and only if it is a ".css" file.

Sign up to request clarification or add additional context in comments.

Comments

0

Late, but maybe it will help someone. :)

Another regex that matches css paths: href[ \t]{0,}=[ \t]{0,}"(.{1,}\.css)"

This also matches cases when between href and = exists tabs or spaces or between = and css filename.

Also, if you want to match css and javascript filenames in one regex you can use something like this: href[ \t]{0,}=[ \t]{0,}"(.{1,}\.css)"|src[ \t]{0,}=[ \t]{0,}"(.{1,}\.js)" They are combined by or operator |.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.