10

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!

2 Answers 2

23

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1, tho you forgot str.replace(/,.*/,''); & str.slice(0,str.indexOf(',')); ;)
4

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

var a = "important, not so important";

a = a.split(",")[0];

2 Comments

this is repeat answer
@miteshkalal Yeah we probably hit submit pretty fast and Felix most likely didn't have a fiddle until it was edited. This is from 2011, 9 years ago so who knows, Stackoverflow was much different then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.