2

I am trying to figure out how to write a regex that would provide the url from a string like this:

'<script type="text/javascript" src="http://chrismills.la/test.js"></script>';

This works, but I need to find a cleaner way to do this:

var url = '';
_content.replace(/src ?= ?"([^"]+)"/gi, function(res) {
    url = res;
    url = url.replace('src=','');
    url = url.replace(/['"]+/g, '')
    url = url.replace(/["']+/g, '')
});
script.src = url;

In action: http://jsfiddle.net/zb3jh180/

SOLUTION, based on answer below:

var regex = /<script.*?src="(.*?)"/gmi;
var url = regex.exec(_content);
script.src = url[1];
user1572796
  • 1,057
  • 2
  • 21
  • 46
  • 2
    Do you have access to the DOM object? Reading the `src` attribute directly would be easier if you do. – dee-see Sep 02 '14 at 20:53
  • You [shouldn't use regexp for that](http://stackoverflow.com/a/1732454/36866)... No... `/https?:\/\/[^"]*/` – some Sep 02 '14 at 21:12
  • No access to the DOM in this case, the scripts are added dynamically with js – user1572796 Sep 02 '14 at 21:33
  • What? What is added to the page? If you want to get the src for every script on the current page you can use something like `for(var i=0, len=document.scripts.length; i < len; ++i) {console.log(document.scripts[i].src)}` – some Sep 03 '14 at 06:40
  • scripts are added as strings from js or an external js file as clearly shown in the code/jsfiddle. It has been answered already. – user1572796 Sep 03 '14 at 17:31

3 Answers3

10

You can use this regex:

<script.*?src="(.*?)"

Working demo

Or also something like:

<script.*?"(http.*?)"

Working demo

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
1

Updated the fiddle, let me know if this was what you are going for. Basically just creating a capture group:

            var srcRegEx = /src="(.*?)"/g;
            var source = srcRegEx.exec(_content);
            script.src = source[1];

http://jsfiddle.net/zb3jh180/1/

tcmurphy
  • 239
  • 2
  • 13
  • Try it on a string like this: `Oh, "SNAP"!` and you see how it fails... it's too greedy. – some Sep 02 '14 at 21:17
0

If you want to match a string of script tags containing "http://chrismills.la" in the src attribute, you can use this Regex:

<script.*?src="(http:\/\/chrismills\.la.*?)"*<\/script>