Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Truncate string after comma

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!

like image 863
user610728 Avatar asked Feb 11 '11 17:02

user610728


2 Answers

You can do it with substring and 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():

str = str.split(',')[0];

this works even without testing beforehand but might perform unnecessary string operations (which is probably negligible on small strings).

like image 143
Felix Kling Avatar answered Oct 23 '22 06:10

Felix Kling


http://www.jsfiddle.net/a5SWU/

var a = "important, not so important";

a = a.split(",")[0];
like image 41
Loktar Avatar answered Oct 23 '22 05:10

Loktar