Petrod Kohli
Petrod Kohli

Reputation: 23

Javascript RegEx -- Selecting everything preceding a character only when ending with a specific phrase

Trying to use RegEx in JavaScript to remove the end of a sentence (string) after a comma, but only when a certain key phrase is ending the sentence.

For example, for key phrase 'StackExchange' and sentence RegEx is confusing me, John told StackExchange.

I want to select just RegEx is confusing me.


For the sentence(s) / string:

They couldn't figure out how to do it with RegEx. They searched for hours all around the web, before asking on StackExchange.

I want to select just:

They couldn't figure out how to do it with RegEx. They searched for hours all around the web.

Thanks for any help.

Upvotes: 1

Views: 56

Answers (1)

Ωmega
Ωmega

Reputation: 43673

Use the regex pattern

^[^,]+(?=,.*StackExchange\.?$)

Test it here.


Or, if you want to check an optional period/dot at the end of the sentence (and store it to group #1), use the pattern

^[^,]+(?=,.*StackExchange(\.?)$)

Test it here.


EDIT:

If you need to match everything before the last occurrence of comma, use

^.+(?=,.*StackExchange(\.?)$)

Test it here.

Upvotes: 2

Related Questions