0

I have this following String below

[01]ABC0007[0d0a]BB BABLOXC[0d0a]067989 PLPXBNS[0d0a02]BBR OIC002 L5U0/P AMD KAP 041800 T1200AND 2+00[0d0a0b03]

And I am attempting to replace all [..] with spaces.

What I have tried.

return this.text.replace(new RegExp('[0d0a] | [0d0a02] | [0d0a02]' ) ,  ' ')
return this.text.replace(new RegExp('\[0d0a\] | \[0d0a02\] | \[0d0a02\]' ) ,  ' ')

What works is only this.

return this.text.replace(new RegExp('0d0a') ,  ' ')

Posts in this one here involve multiple steps. This is going to be used as input as 'javascript' string to the Bson filter for mongo queries since mongo does not yet have REPLACE function like SQL has. There is a open request.

HVA
  • 43
  • 6

2 Answers2

2

You need to escape your brackets: \[\]. Also, you can check for anything between the brackets (non-greedy): \[.*?\]:

let string = `[01]ABC0007[0d0a]BB BABLOXC[0d0a]067989 PLPXBNS[0d0a02]BBR OIC002 L5U0/P AMD KAP 041800 T1200AND 2+00[0d0a0b03]`;

let replaced = string.replace(/\[.*?\]/g, ' ');

console.log(replaced);
KevBot
  • 17,900
  • 5
  • 50
  • 68
0

You have to escape the opening bracket \[ if you want to match for example [0d0a]. In your second regex you have to remove the whitespace before and after the | because it has meaning.

Your regex would look like:

\[0d0a]|\[0d0a02]|\[0d0a02]

let str = "[01]ABC0007[0d0a]BB BABLOXC[0d0a]067989 PLPXBNS[0d0a02]BBR OIC002 L5U0/P AMD KAP 041800 T1200AND 2+00[0d0a0b03]";
console.log(str.replace(/\[0d0a]|\[0d0a02]|\[0d0a02]/g, ' '));

If you want to match all from opening till closing bracket you could use:

\[[^\]]+]

That would match from [ till ] and matches what is between using a negated character class [^[]+ which will match not a ] one or more times.

let str = "[01]ABC0007[0d0a]BB BABLOXC[0d0a]067989 PLPXBNS[0d0a02]BBR OIC002 L5U0/P AMD KAP 041800 T1200AND 2+00[0d0a0b03]";
console.log(str.replace(/\[[^\]]+]/g, ' '));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70