0

I want to remove letters from (a1-800-b-400), but naively doing so results in (1-800--400).

How do I get (1-800-400)?

If it involves RegExp, please explain how it works.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
Chen
  • 2,958
  • 5
  • 26
  • 45
  • 1
    Yes, the solution is a regex. It's really simple, why don't you try to write it yourself? Hint: `[^...]` matches any characters that aren't in `...` – Barmar May 11 '20 at 13:09
  • 1
    hold on, you said any character not numeric, bracket or hyphen, then your example removes a hyphen! – Jamiec May 11 '20 at 13:10
  • 2
    Shouldn't the result be `(1-800--400)`? Do you also want to collapse multiple hyphens into a single hyphen after removing other characters? – Barmar May 11 '20 at 13:11
  • That's also a simple regular expression. – Barmar May 11 '20 at 13:12
  • 1
    "(a1-800-b-400)".replace(/[^ \-( 0-9)]/g,'').replace(/\-\-+/g,'-')==="(1-800-400)" – QuentinUK May 11 '20 at 18:03

1 Answers1

0

This is the RegExp you need:

/[^\d\()-]/g

/ / are simply indicators that you're writing a RegExp literal.

The trailing g flag means find all matches, instead of just one.

Everything between the [ ] are the characters you want to match.

But the ^ symbol means the opposite; don't match.

\d means Number, \( means open parenthesis (escaped), ) is obvious, as is -.

const regExpA = /[^\d\()-]/g;
const regExpB = /--/g;
const string = '(a1-800-b-400)';
const result = string
  .replace(regExpA, '')   // (1-800--400)
  .replace(regExpB, '-'); // (1-800-400)

console.log(result);
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43