2

Forgive me if this is a double post, but I couldn't find a similair one that worked for me.

I have a domain name ex. google.co.uk (but this can also be google.com). I need to split this on the first period so I get an array object like this: ["google", "co.uk"] or ["google", "com"]

In antoher post I found this: 'google.co.uk'.split(/.(.+)?/)[1]; but that doesn't seem to work...

Can anyone help me? Thanks in advance!

Guido Visser
  • 2,209
  • 5
  • 28
  • 41

4 Answers4

6

Replace the first . with something else that will never turn up in the string (such as |), then split off that character.

As str.replace only replaces the first instance of the character it finds by default, the code is pretty simple:

str = "google.co.uk";
str.replace(".", "|").split("|");
Doug
  • 3,312
  • 1
  • 24
  • 31
0

jsFiddle

var text = 'google.co.uk';

//Returns the position of the first '.'
var index = text.indexOf('.');

//Grab the the start of the string up to the position of the '.'
var first = text.substring(0, index);

//Start from the '.' + 1(to exclude the '.') and go to the end of the string
var second = text.substring(index + 1);

alert(first); //google
alert(second); //co.uk
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
0

You're all making this a bit complicated. It's possible in one easy line:

var domain = 'google.co.uk';
alert(domain.split(/^(.+?)\./ig).splice(1));
Wildhoney
  • 4,969
  • 33
  • 38
0

You can use some native javascript functions...

string='google.com';
dot=string.indexOf('.',0);


name=string.substring(0,dot);
domain=string.substring(dot+1,string.length);

arr= new Array(name, domain);
alert(arr);

Lol, already see better solutions... :) and similar solutions too...

sinisake
  • 11,240
  • 2
  • 19
  • 27