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
RegEx Explanation:
(?:src|href)=
: Match src=
or href=
("|')
: Match single quote '
or double quote "
and add this into first captured group. .*?
: Match any characters lazily to satisfy condition ([\\w.]+\\.(?:js|css))
: Second captured group
[\\w.]+\\.
: Match any alphanumeric character and underscore one or more times followed by dot. (?:js|css)
: Match js
or css
. \\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.