2011-05-31 37 views

回答

4

如何拆分:

var string = 'Doyletown, PA'; 
var parts = string.split(','); 
if (parts.length > 0) { 
    var result = parts[0]; 
    alert(result); // alerts Doyletown 
} 
+0

什么?长度将始终大于或等于1!这不是一个很好的例子,我也不会建议使用一个方法来创建整个数组,并且在内部必须遍历整个字符串,即使它立即发现“,”。 – Jonathon 2011-05-31 22:52:15

6
var str = 'Doyletown, PA'; 
var newstr=str.substring(0,str.indexOf(',')) || str; 

我加入了|| str来处理情况,该字符串没有逗号的情景

+1

@teneff +1,删除了我的版本。 – arcain 2011-05-31 22:21:21

+0

+1,这里最好的方法 – Jonathon 2011-05-31 22:54:34

1

使用常规e上的表达就会像:

var str = "Doyletown, PA" 
var matches = str.match(/^([^,]+)/); 
alert(matches[1]); 

jsFiddle

BTW:我也宁愿.split()方法

+0

这应该是'匹配[0]'。 ''[1]'因为没有使用'g'匹配而不存在。 – Jonathon 2011-05-31 22:56:59

0

或更普遍(获得以逗号分隔列表中的所有的话):

//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace. 
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g); 
0

试试这个:

str = str.replace(/,.*/, ''); 

或玩这个jsfiddle