views:

49

answers:

1

I have a string called myString that contains some part the end that I do not want:

var myString = 'The sentence is good up to here foo (bar1 bar2)';
var toBeRemoved = 'foo (bar1 bar2)';

How can I use best JavaScript regex to remove the part I don't want. The method replace() seems to have a problem with the parentheses.

Edit:

I did try to escape ( and ) like Matthew said. I thought that didn't work, but now just tried again and it did.

var myString = 'The sentence is good up to here foo (bar1 bar2)';
var toBeRemoved = 'foo (bar1 bar2)';
document.write(myString .replace(/foo \(bar1 bar2\)/i, ''));

Thanks Matthew.

+2  A: 

You need to escape the parens as \( and \). E.g.

myString.replace(/\w+\s+\(.*?\)/, "")
Matthew Flaschen
I thought I did that but that didn't work, but I just tried again and it did.
cathat
cathat, maybe you were using the `RegExp` constructor. In that case you need to double escape parens (and other characters).
Matthew Flaschen