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];
5
  • 2
    Do you have access to the DOM object? Reading the src attribute directly would be easier if you do. Commented Sep 2, 2014 at 20:53
  • You shouldn't use regexp for that... No... /https?:\/\/[^"]*/ Commented Sep 2, 2014 at 21:12
  • No access to the DOM in this case, the scripts are added dynamically with js Commented Sep 2, 2014 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)} Commented Sep 3, 2014 at 6: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. Commented Sep 3, 2014 at 17:31

3 Answers 3

10

You can use this regex:

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

Working demo

Or also something like:

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

Working demo

Sign up to request clarification or add additional context in comments.

2 Comments

This one here is more stable and does not return false positives like <script></script><img src="not-wanted.jpg"/>: /<script[a-z1-9"'\/ =]*?src="(.*?)"/gmi
@Andreas How could this be altered to allow for single quotes as well.
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/

1 Comment

Try it on a string like this: <tag src="link1" alt="text">Oh, "SNAP"!</tag> and you see how it fails... it's too greedy.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.