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,102
  • 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
  • 233,373
  • 50
  • 316
  • 318
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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

First, be warned.

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

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

Community
  • 1
  • 1
robert
  • 33,242
  • 8
  • 53
  • 74
0

Try:

match(`<link .*?href="\/assets\/(?:[^\/]*\/)*(.*?\.css)"/i)
codaddict
  • 445,704
  • 82
  • 492
  • 529
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,061
  • 5
  • 49
  • 46