Huxley
Huxley

Reputation: 31

Using replace and regex to remove characters from this string

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.

Upvotes: 3

Views: 62

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174706

Use capturing group.

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

Upvotes: 3

Guffa
Guffa

Reputation: 700332

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);

Upvotes: 0

Imab Asghar
Imab Asghar

Reputation: 316

Try using string as mentioned by Tushar.

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

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);

Upvotes: 0

Related Questions