【问题标题】:jQuery strip first period [duplicate]jQuery剥离第一期[重复]
【发布时间】:2013-01-26 12:48:31
【问题描述】:
如果这是一个重复的帖子,请原谅我,但我找不到适合我的类似帖子。
我有一个域名 ex。 google.co.uk(但也可以是 google.com)。我需要在第一阶段拆分它,所以我得到一个这样的数组对象:["google", "co.uk"] 或 ["google", "com"]
在另一个帖子中我发现了这个:'google.co.uk'.split(/.(.+)?/)[1]; 但这似乎不起作用...
谁能帮帮我?提前致谢!
【问题讨论】:
标签:
javascript
jquery
split
【解决方案1】:
替换第一个 .用其他永远不会出现在字符串中的东西(例如 |),然后拆分该字符。
由于 str.replace 默认只替换它找到的字符的第一个实例,因此代码非常简单:
str = "google.co.uk";
str.replace(".", "|").split("|");
【解决方案2】:
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
【解决方案3】:
你们都让这有点复杂。一条简单的线就可以实现:
var domain = 'google.co.uk';
alert(domain.split(/^(.+?)\./ig).splice(1));
【解决方案4】:
你可以使用一些原生的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);
大声笑,已经看到了更好的解决方案... :) 以及类似的解决方案...