Bluga
Bluga

Reputation: 39

Javascript - how to remove .com or .net or .org from location.href

I need to remove .com or any domain type from location.href for example:

sub.domain.com

and I need to return

sub.domain

Thanks!

Upvotes: 1

Views: 1425

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Simple Regex solution :

"sub.domain.com".replace(/([.]\w+)$/, '')

[.] : the literal character .
\w+ : match any word character [a-zA-Z0-9_]
Quantifier: + Between one and unlimited times, as many times as possible
$   : assert position at end of the string

Hope this helps.


alert("sub.domain.com".replace(/([.]\w+)$/, ''));

Hope this helps.

Upvotes: 0

mstruebing
mstruebing

Reputation: 1812

You can use lastIndexOf and substring

var str = 'sub.domain.com';
var end = str.lastIndexOf('.');
return str.substring(0, end);

A full function would look as simple as following:

function stripTopLevelDomain(var domain) {
  return domain.substring(0, domain.lastIndexOf('.'));
}

Upvotes: 1

CoderPi
CoderPi

Reputation: 13211

The simple way: (no RegeEx needed)

var url = "sub.domain.com"
url = url.substring(0, url.lastIndexOf("."))

document.write(url)

Upvotes: 1

Related Questions