javascript javascript在逗号后截断字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4971961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript Truncate string after comma
提问by user610728
I'm looking for a way to remove the comma and all that comes after it in a string, for example:
我正在寻找一种方法来删除逗号及其后的所有字符串,例如:
important, not so important
重要,不那么重要
I'd like to remove ",not so important"
我想删除“,不那么重要”
Any ideas? Thanks in advance!
有任何想法吗?提前致谢!
回答by Felix Kling
You can do it with substringand indexOf:
str = str.substring(0, str.indexOf(','));
but you'd have to be sure that a comma is in there (test it before).
但你必须确保逗号在那里(之前测试过)。
Another possibility is to use split():
另一种可能性是使用split():
str = str.split(',')[0];
this works even without testing beforehand but might perform unnecessary string operations (which is probably negligible on small strings).
即使没有事先测试,这也能工作,但可能会执行不必要的字符串操作(这在小字符串上可能可以忽略不计)。
回答by Loktar
http://www.jsfiddle.net/a5SWU/
http://www.jsfiddle.net/a5SWU/
var a = "important, not so important";
a = a.split(",")[0];

