0

I am building a naive rstrip function. And it works properly like this when I hardcode the actual characters:

const rstrip = (s, chars) => s.replace(/[r!]+$/g, "");
console.log(rstrip("Hello!!!!r", '!r'))

However, if I try and use the chars variable, I have trouble escaping it:

const rstrip = (s, chars) => s.replace(/[chars]+$/g, "");
console.log(rstrip("Hello!!!!r", '!r'))

What would be the proper way to 'escape' the variable so that the value !r replaces the chars variable in the replace method?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • Your question doesn't seem to be about escaping, it's about how to substitute a variable in a regexp. – Barmar Oct 09 '21 at 03:13

1 Answers1

2

const rstrip = (s, chars) => s.replace(new RegExp(`[${chars}]+$`, 'g'), "");
console.log(rstrip("Hello!!!!r", '!r'))
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • 1
    This won't work properly if `chars` contains `]`, `-` because they have special meaning inside `[]` – Barmar Oct 09 '21 at 03:12