[javascript] 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?

This question is related to javascript string

The answer is

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

Either manually, like

var str = "www.test.com",
    rmv = "www.";

str = str.slice( str.indexOf( rmv ) + rmv.length );

or just use .replace():

str = str.replace( rmv, '' );

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

Try the following

var original = 'www.test.com';
var stripped = original.substring(4);

You can overload the String prototype with a removePrefix function:

String.prototype.removePrefix = function (prefix) {
    const hasPrefix = this.indexOf(prefix) === 0;
    return hasPrefix ? this.substr(prefix.length) : this.toString();


const domain = "www.test.com".removePrefix("www."); // test.com

If the string has always the same format, a simple substr() should suffice.

var newString = originalStrint.substr(4)

Yes, there is a RegExp but you don't 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);