Reputation: 14406
Given any sentence with a comma:
var myText = 'This is mine, all of it, and more!'
I'd like to remove everything after the first comma, including the word preceding it.
The above example would output:
This is
If there's no comma, everything should be returned.
I assume I'll need to use something along the lines of, but not sure where to go from here:
myText.replace(/.*,/, "");
Upvotes: 1
Views: 152
Reputation: 31339
Well, I find regular expressions unreadable, so perhaps consider:
if (str.indexOf(',') != -1){
/*
parts = str.split(',')
words = parts[0].split(' ')
# remove last word and re-join
return words.slice(0, -1).join(' ');
*/
return str.split(',')[0].split(' ').slice(0,-1).join(' ');
}
return str;
Upvotes: 0
Reputation: 785156
You can do:
var str = "This is mine, all of it, and more!";
str = str.replace(/ *\b[^, ]+,.*/, "");
//=> This is
Upvotes: 2