3

Need to get the css file name from a link tag that is in a specific folder.

<link href="/assets/49f0ugdf8g/sub/style.css"   -> style.css

Currently have

match(`<link .*?href="\/assets\/(.*?\.css)"/i)

Which returns the path minus "/assets/".
Can it be extended to remove the rest of the path and just return the file name.

Alex
  • 2,092
  • 1
  • 13
  • 16

5 Answers5

3

It would be simpler not to use regex and to use the native JS String.split function:

var link = document.getElementsByTagName('link')[0]; // or whatever JS to get your link element
var filename = link.href.split('/').pop(); // split the string by the / character and get the last part
lonesomeday
  • 224,675
  • 49
  • 309
  • 312
0

Sure:

match(<link .*?href="\/assets\/([^/]+\.css)"/i)
//                              ^^^^^ change here

I dropped the ? because you probably want the capture group to be greedy. Also used + rather than * on the assumption there will always be at least one character in the "file" name.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

First, be warned.

Try this: "\/assets\/(?:[^\/">]+\/)*([^\/">]*?.css)".

The (?:...) is a non-capturing group.

Community
  • 1
  • 1
robert
  • 31,344
  • 8
  • 51
  • 72
0

Try:

match(`<link .*?href="\/assets\/(?:[^\/]*\/)*(.*?\.css)"/i)
codaddict
  • 429,241
  • 80
  • 483
  • 523
0
var link = '<link href="/assets/49f0ugdf8g/sub/style.css">';
var match = link.match(/<link .*?href="(.*)">/i);
var filename = match[1].split('/').pop();
Vojta
  • 23,021
  • 5
  • 48
  • 46