0

How do you trim all of the text after a comma using JS?

I have: string = Doyletown, PA

I want: string = Doyletown

5 Answers 5

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

I added the || str to handle a scenario where the string has no comma

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

1 Comment

@teneff +1, removed my version.
4

How about a split:

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

1 Comment

What? the length will always be greater then or equal to 1! This is not a very well done example nor would I suggest using a method that makes an entire array and will internally have to iterate through the entire string even if it finds a "," right away.
1

using regular expression it will be like:

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

jsFiddle

btw: I would also prefer .split() method

1 Comment

That should be matches[0]. [1] does not even exist because you did not use a g match.
0

Or more generally (getting all the words in a comma separated list):

//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);

Comments

0

Try this:

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

Or play with this jsfiddle

Comments

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.