Home > Net >  Javascript - How to remove texts in between brackets
Javascript - How to remove texts in between brackets

Time:03-07

I'd like to know a simple way to change:

My name[1] is David Smith[ref.2] and my home is in Auburn[Geo-Ref3], AL.

into

My name is David Smith and my home is Auburn, AL.

If I do

string.replace(/\[.*\]/g, "")

then I get

My name, AL.

Thanks.

CodePudding user response:

.* will match greedily (as much as possible) by default. So the regex matched

My name[1] is David Smith[ref.2] and my home is in Auburn[Geo-Ref3], AL.
       ^----------------------------------------------------------^

You want to match reluctantly (as little as possible), which has syntax .*?. So use string.replace(/\[.*?\]/g, ""). This will match

My name[1] is David Smith[ref.2] and my home is in Auburn[Geo-Ref3], AL.
       ^-^               ^-----^                         ^--------^
  • Related