4

Here is my variable from which I want to extract only URL, for example in this case I want at the end the result: http://url.com/index.php/foo/bar/new/key/34941cd947592adb1594b6f649468a33/

var variable = "function onclick(event) { setLocation('http://url.com/index.php/foo/bar/new/key/34941cd947592adb1594b6f649468a33/')}"
sh00pac
  • 43
  • 1
  • 1
  • 3
  • 2
    Why are you storing JavaScript as a string in a JavaScript variable? Functions are objects too, you can just assign them to variables `var foo = function(){}` – elclanrs Sep 06 '13 at 02:31
  • @elclanrs If he did it as a function instead of string, how would he extract the URL from it? – Barmar Sep 06 '13 at 02:41
  • @Barmar I think what he meant to ask is how that variable ended up with a piece of code inside. – Ja͢ck Sep 06 '13 at 02:42

1 Answers1

12

Use this:

var testUrl = variable.match(/'(http:[^\s]+)'/),
    onlyUrl = testUrl && testUrl[1];

The onlyUrl variable contains the extracted URL or null.

EDIT:

Previous was just answer to OP. Following an update to take care of https:

var testUrl = variable.match(/'(https?:[^\s]+)'/),
    onlyUrl = testUrl && testUrl[1];
1111161171159459134
  • 1,106
  • 2
  • 14
  • 25