So I have a string and I want to take a part of the string, that it matches. For example:
stringToFind:
"<html><head><script src="http://example.com"></script>..."
I need to get the source of the script tag. I need to find all instances of the script tag in the string, and get the url of the source.
I was going to use String.prototype.replace(), that uses regular expressions, but you have to replace it with something and the result is the whole string.
2
Answers
javascript is pretty good at handling HTML markup, so you probably don’t need a regex here.
this should do the trick:
if you need to extract script tags from the DOM in the browser, then you only need this:
console.log( Array.from(document.querySelectorAll('script[src]')).map((s) => s.getAttribute('src')) );
side note:
// <!--
and// -->
is there to make the jsfiddle run (which it wont reliably when containing html code in strings) as suggested by @InSync