Delete line at the beginning of the URL

I want to remove the β€œ www. ” Part from the beginning of the URL string

For example, in these test cases:

eg. www.test.com β†’ test.com
e.g. www.testwww.com β†’ testwww.com
e.g. testwww.com β†’ testwww.com (if it does not exist)

Do I need to use Regexp or is there an intelligent feature?

+49
javascript string
Mar 29 '12 at 15:34
source share
6 answers

Depending on what you need, you have several options:

 // this will replace the first occurrence of "www." and return "testwww.com" "www.testwww.com".replace("www.", ""); // this will slice the first four characters and return "testwww.com" "www.testwww.com".slice(4); // this will replace the www. only if it is at the beginning "www.testwww.com".replace(/^(www\.)/,""); 
+108
Mar 29 '12 at 15:37
source share

If the string always has the same format, simple substr() enough.

 var newString = originalStrint.substr(4) 
+7
Mar 29 2018-12-12T00:
source share

Or manually, for example

 var str = "www.test.com", rmv = "www."; str = str.slice( str.indexOf( rmv ) + rmv.length ); 

or just use .replace() :

 str = str.replace( rmv, '' ); 
+3
Mar 29 '12 at 15:37
source share

Yes, there is RegExp, but you do not need to use it or any "smart" function:

 var url = "www.testwww.com"; var PREFIX = "www."; if (url.indexOf(PREFIX) == 0) { // PREFIX is exactly at the beginning url = url.slice(PREFIX.length); } 
+2
May 27 '16 at 18:07
source share

Try to execute

 var original = 'www.test.com'; var stripped = original.substring(4); 
0
Mar 29 2018-12-12T00:
source share

You can cut off the url and use response.sendredirect (new url), this will lead you to the same page with the new url

0
Mar 29 '12 at 15:37
source share



All Articles