-1

I am trying to replace 2% with ''(empty) using regexp concept. If input string is either % or 2%, it should be replaced with ''(empty):

const str = "2%";

console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));

(a|b) Matches the a or the b part of the subexpression.

"2%".replace(/^\d%$|\d(?=%)/, ''). This works well.

But, "2%".replace(/\d(?=%)|^\d%$/, '') does not.

HarshvardhanSharma
  • 754
  • 2
  • 14
  • 28

1 Answers1

2

The difference is in what the regex tries to match first. The left expression takes precedence. The right is only tried when the left one fails to match.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375