3

I am trying to remove the brackets and 'url' from a string similar to this:

url('http://www.stackoverflow.com');

So it would just leave 'http://www.stackoverflow.com'

The furthest I have got to getting this working is

var myvar = url('http://www.stackoverflow.com');
myvar = myvar.replace(/[url()]/g, '');

But obviously this would mean that any 'u', 'r', or 'l' would be removed from the actual domain.

I guess the answer would be to only remove the first instance of each of the characters.

1
  • var myvar = "url('http://www.stackoverflow.com')"; wrap in quotes to make it string. Open browser console to check errors Commented Aug 28, 2015 at 6:52

4 Answers 4

3

Use capturing group.

var string = "url('http://www.stackoverflow.com')";
var url =   string.replace(/\burl\('([^()]*)'\)/g, "$1")
document.write(url) 

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

5 Comments

The real problem is with the myvar. It is not string that contains url, it is something returned by function url()
var myvar = "url('http://www.stackoverflow.com')"; myvar = myvar.replace(/[url()]/g, ''); Execute in console
@Tushar ya, it seems like a typo.
@Tushar I am trying to remove the brackets and 'url' from a string similar to this: Its a string only
@NarendraSisodia Can you please read the previous comments here. var myvar = "url('http://www.stackoverflow.com')"; myvar = myvar.replace(/[url()]/g, ''); Execute in console
0

You can use a non-regex replace since you are remove just once:

var myvar = "url('http://www.stackoverflow.com')";
myvar = myvar.replace("url('", '').replace("')", "");
document.write(myvar);

For the regex-iacs:

var myvar = "url('http://www.stackoverflow.com')";
myvar = myvar.replace(/^url\('|'\)$/g, '');
document.write(myvar + "<br/>");

 // or even
var myvar = "url('http://www.stackoverflow.com')";
myvar = myvar.replace(/\bUrl\('|'\)/ig, '');
document.write(myvar);

2 Comments

The real problem is with the myvar. It is not string that contains url, it is something returned by function url()
@Tushar: I believe that is an OP's typo, and it is a string. Otherwise, the original code does not compile.
0

Try using string as mentioned by Tushar.

var myvar = "url('http://www.stackoverflow.com')";
myvar = myvar.replace(/[url()]/g, '');

Comments

0

If you know that the string always has that format, you don't need to replace, you can just remove the characters from the start and end:

myvar = myvar.substr(5, myvar.length - 8);

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.