kylex
kylex

Reputation: 14406

Remove all text after first occurence of character, including any characters preceding that don't have a space

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

Answers (2)

Reut Sharabani
Reut Sharabani

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

anubhava
anubhava

Reputation: 785156

You can do:

var str = "This is mine, all of it, and more!";
str = str.replace(/ *\b[^, ]+,.*/, "");
//=> This is

RegEx Demo

Upvotes: 2

Related Questions