简体   繁体   中英

javascript regex for filename in import script (js/css)

i have a string containing some HTML code:

var myString = '<html> ... <script src="/cmn/libs/js/myJavascriptFile.js"></script> 
<link rel="stylesheet" href="../assets/myCssFile.css"/> ... </html>';

and i want to match all the imported files without the PATH, like this: myJavascriptFile.js , myCssFile.css

i tried with this regex

var myRegexp = /src="(.*)"|href="(.*)"/g;
var match = myRegexp.exec(myString);

but it gives me the entire path, and i guess it will fail if import has single quote. What's the best approach here? thanks

this is the test i did: https://regex101.com/r/gL8lO7/2

 var html = document.getElementById("data").value; var res = []; html.replace(/(?:src|href)=(["'])(?:.*?)([^\\\\/"]*?)\\1/g, function (match, quote, name) { res.push(name); }) console.log(res); 
 textarea { display: block; width: 100%; } 
 <textarea id=data><html> ... <script src="/cmn/libs/js/myJavascriptFile.js"></script> <link rel="stylesheet" href='../assets/myCssFile.css'/> ... </html></textarea> 

You can use following regex.

(?:src|href)=("|').*?([\w.]+\.(?:js|css))\1

RegEx101 Demo

RegEx Explanation:

  1. (?:src|href)= : Match src= or href=
  2. ("|') : Match single quote ' or double quote " and add this into first captured group.
  3. .*? : Match any characters lazily to satisfy condition
  4. ([\\w.]+\\.(?:js|css)) : Second captured group
    1. [\\w.]+\\. : Match any alphanumeric character and underscore one or more times followed by dot.
    2. (?:js|css) : Match js or css .
  5. \\1 : Back-reference to first captured group. Match the same thing in the first captured group. ie single or double quote.

Demo:

 var str = '<script src="\\/cmn\\/libs\\/js\\/myJavascriptFile.js"><\\/script><link rel="stylesheet" href="..\\/assets\\/myCssFile.css" \\/><script src=\\'\\/cmn\\/libs\\/js\\/myJavascriptFile.min.js\\'><\\/script><link rel="stylesheet" href=\\'0..\\/assets\\/myCssFile.css\\'\\/>'; var allFiles = []; var regex = /(?:src|href)=("|').*?([\\w.]+\\.(?:js|css))\\1/gi; var fileName = ''; while(fileName = regex.exec(str)) { allFiles.push(fileName[2]); } console.log(allFiles); 

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