简体   繁体   中英

How to remove string in double brackets?

I want to know how can I remove the string in double brackets & including brackets. Here's an example

var str="(C84) [Yayui (shirogisu)] 1 Day with the Commodore";
var n = str.replace(/\s*\(.*?\)\s*/g, '')
alert(n);

So far it only removed single brackets but not the one with brackets inside another bracket. The final output should look like this:

1 Day with the Commodore

How can I remove the string in any type of brackets such as {,},[,],(,) Live version: http://jsfiddle.net/aPa25/

Not sure what you mean by double brackets, but to remove all the stuff in both parens and square braces you could use

str.replace(/\s*\(.*?\)\s*/g, '').replace(/\s*\[.*\]\s*/g, '')

The first replace removes everything in parentheses, the second removes everything in square braces.

Additionally, if you know the form of your input is always going to be like that, ie a parenthetical part followed by a square braced part, you could just do:

str.replace(/^\s*\(\w+\)\s*\[.*\]\s*/, '')

It's less general but might be more robust if that assumption is true.

EDIT: Given that there can be other paren and square braces later in the text that you want to keep, try:

str.replace(/\s*\([^)]*\)\s*/g, '').replace(/\s*\[[^\]]*\]\s*/g, '')

If you say there can be square braces nested within the first square braces, I will say that, mathematically, you will require a more powerful theoretical machine than a finite state machine (regex).

This should work as the replace regex. It looks individually for each of the bracket types.

\s*(?:\[[^[]+]|\([^)]+\)|{[^}]+})\s*

Edit: I think the "nesting order" needs to be the same as in the regex, so it may require re-ordering of the alternation if what I have is wrong. However, it does work on your examples.

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