Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub a string in javascript

Tags:

javascript

I try to get only the domain name i.e. google.com from javascript

document.location.hostname

This code returns www.google.com.

How can I only get google.com? In this case it would be to either remove the www. or get only the domain name (if there's such a method in javascript).

like image 219
Martin Avatar asked Dec 22 '12 01:12

Martin


People also ask

How to replace a letter in a string in JavaScript?

You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.

How to modify string in JavaScript?

Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character. in fact every occurence of the same string is ONE object.

How do you cut a string in JavaScript?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.

How do you replace all occurrences of a character in a string in JavaScript?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.


2 Answers

var host = location.hostname.replace( /www\./g, '' );

The 'g' flag is for 'global', which is needed if you want a true "gsub" (all matches replaced, not just the first).

Better, though, would be to get the full TLD:

var tld = location.hostname.replace( /^(.+\.)?(\w+\.\w+)$/, '$2' );

This will handle domains like foo.bar.jim.jam.com and give you just jam.com.

like image 188
Phrogz Avatar answered Oct 03 '22 14:10

Phrogz


... I'm in chrome right now, and window.location.host does the trick.

EDIT

So I'm an idiot... BUT hopefully this will redeem:

An alternate to regex:

var host = window.location.hostname.split('.')
    .filter(
        function(el, i, array){
            return (i >= array.length - 2)
        }
    )
    .join('.');
like image 34
freethejazz Avatar answered Oct 03 '22 15:10

freethejazz