简体   繁体   中英

Remove parenthesis brackets-( and ) from string in JavaScript

I have a string which contains characters ( and ) . I want to replace those characters with "" .

I tried using

str.replace(/(|)/g,"")

And

str.replace(/'('|')'/g,"")

But they are not working

As the characters ( and ) has special meaning in RegEx( capturing groups ), they need to be escaped by preceding with backslash to match the brackets literally.

str.replace(/\(|\)/g, "")
             ^  ^

 var str = 'Lorem ipsum dolor (sit) amet, consectetur (adipisicing) elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad (minim) veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure (dolor) in reprehenderit in (voluptate) velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in (culpa) qui officia deserunt mollit anim id est laborum.'; str = str.replace(/\\(|\\)/g, ''); document.body.innerHTML = str; 

You can also use parenthesis inside character class [()] , where ( and ) are treated as literals.

str.replace(/[()]/g, '');

 var str = 'Lorem ipsum dolor (sit) amet, consectetur (adipisicing) elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad (minim) veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure (dolor) in reprehenderit in (voluptate) velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in (culpa) qui officia deserunt mollit anim id est laborum.'; str = str.replace(/[()]/g, ''); console.log(str); document.body.innerHTML = str; 

Because you are using regular expressions the () characters are special characters.

You can however, put them in a character group, where they do not need to be escaped.

str.replace(/[()]/g,"")

您需要使用\\字符对()字符进行转义,如下所示:

str.replace(/(\(|\))/g, "");

您需要转义()

str.replace(/\(|\)/g,"")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM