2013-02-11 50 views
2

請原諒我,如果這是一個雙後,但我找不到一個適合我的similair。jQuery strip first period

我有一個域名前。 google.co.uk(但這也可以是google.com)。我需要讓我得到這樣一個數組對象拆分此第一期:["google", "co.uk"]["google", "com"]

在antoher後,我發現這一點:'google.co.uk'.split(/.(.+)?/)[1];但似乎並沒有工作......

任何人都可以幫我?提前致謝!

回答

6

替換第一個。用別的東西永遠不會出現在字符串中(比如|),然後分開那個字符。

由於str.replace只替換它發現默認的字符的第一個實例,該代碼非常簡單:

str = "google.co.uk"; 
str.replace(".", "|").split("|"); 
+0

啊,那麼簡單,爲什麼我沒想到呢?!非常感謝你! – 2013-02-11 12:36:26

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 
+0

A -1沒有評論改進和代碼的作品?好奇... – 2013-02-12 16:58:16

0

你做的所有這有點複雜。它可能在一個簡單的一行:

var domain = 'google.co.uk'; 
alert(domain.split(/^(.+?)\./ig).splice(1)); 
0

你可以使用一些本地JavaScript函數...

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

大聲笑,已經看到更好的解決方案... :)和類似的解決方案太...