开发者

Using JavaScript regex to strip substring that contains parentheses

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 .开发者_如何学JAVAreplace(/foo \(bar1 bar2\)/i, ''));

Thanks Matthew.


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

myString.replace(/\w+\s+\(.*?\)/, "")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜