Lukas Lukas - 4 months ago 8
Javascript Question

Remove the string on the beginning of an URL

I want to remove the "

www.
" part from the beginning of an URL string

For instance in these test cases:

e.g.
www.test.com
test.com


e.g.
www.testwww.com
testwww.com


e.g.
testwww.com
testwww.com
(if it doesn't exist)

Do I need to use Regexp or is there a smart function?

Answer

Depends on what you need, you have a couple of choices, you can do:

"www.testwww.com".replace("www.", ""); //this will replace the first occurrence of "www." and return "testwww.com"

"www.testwww.com".slice(4); //this will slice the first four characters and return "testwww.com"

"www.testwww.com".replace(/^(www\.)/,"");  //this will replace the www. only if it is at the beginning