Lupo
Lupo

Reputation: 3094

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.comtest.com
e.g. www.testwww.comtestwww.com
e.g. testwww.comtestwww.com (if it doesn't exist)

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

Upvotes: 218

Views: 225924

Answers (9)

talnicolas
talnicolas

Reputation: 14053

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

var newString = originalString.substr(4)

Upvotes: 11

Archibald
Archibald

Reputation: 1403

const removePrefix = (value, prefix) =>
   value.startsWith(prefix) ? value.slice(prefix.length) : value;

Upvotes: 10

berezovskyi
berezovskyi

Reputation: 3481

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.startsWith(PREFIX)) {
  // PREFIX is exactly at the beginning
  url = url.slice(PREFIX.length);
}

Upvotes: 68

piris
piris

Reputation: 1595

Another way:

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

Upvotes: -2

Flavien Volken
Flavien Volken

Reputation: 21259

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

usage:

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

Upvotes: 4

nicosantangelo
nicosantangelo

Reputation: 13716

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

// 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\.)/,"");

Upvotes: 407

jAndy
jAndy

Reputation: 235962

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

Upvotes: 7

Ofer
Ofer

Reputation: 5209

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

Upvotes: 0

JaredPar
JaredPar

Reputation: 754525

Try the following

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

Upvotes: 2

Related Questions