christophe christophe - 1 year ago 112
Javascript Question

RegEx javascript, character whitespace round bracket

I have the following string in javascript:

"Hallo OR, I am OR )"

Note the space before the bracket.
I want to have this

"Hallo OR, I am )"

So basically just remove the last OR. I tried every RegEx combination without success, i.e.:

string = string .replace(/OR\s\)/, " )"); //NO
string = string .replace(/OR \)/, " )"); //NO

Removing the round bracket only works, but as soon as I add the OR, no luck

string = string .replace(/\)/, " )"); //Removes the bracket
string = string .replace(/\s\)/, " )"); //Removes the bracket and the space

I tried the RegEx /OR\s)/ at and it works nicely, so why not in javascript?

It feels like a very simple problem but after 2 hours I am still lost.

Thanks for your help.

Answer Source
string = string.replace(/(\s*OR)(?![\s\S]*OR)/,"");

See Using Regex to replace last occurrence of a pattern

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download