Jordash
Jordash

Reputation: 3103

Replace outer wrapping brackets with a prefix

I have a string that could look like this

More text here ID[20] [Choice 5] More text here

I need to convert it to this

More text here 20 [Choice 5] More text here

Essentially I need to remove any outer wrapping ID[num] and preserve the number inside.

I did this:

string.replace(/ID\[/g, ' ')

And that removes the ID[ at the start, but I can't figure out how to remove the trailing ]

Upvotes: 0

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

Use

s = s.replace(/ID\[(\d+)]/g, '$1')

See the regex demo

Details

  • ID\[ - a literal string ID[
  • (\d+) - Group 1: one or more digits
  • ] - a literal ]

The $1 is a backreference to the Group 1 value. That is, it will remove all but the digits inside the ID[...].

To match ID as a whole word, add \b before ID (to avoid replacing similar matches, as in CREATIONID[5]).

JS demo:

var s = "More text here ID[20] [Choice 5] More text here";
s = s.replace(/ID\[(\d+)]/g, "$1");
console.log(s);

Upvotes: 3

Related Questions