Joe
Joe

Reputation: 91

How do I remove spaces, brackets and everything in between using REGEX in Javascript

Cant seem to find the same question on here, so here goes,

my string that i want to edit is: +44 (0)1234 123321 I want to remove:

  1. All spaces
  2. Both brackets
  3. Anything inside the brackets

So it should output as +441234123321

How?

Ive already tried:

const phoneRaw = phone.replace(/\([^\)\(]*\)/, ""); const phoneRaw = phone.replace(/[( )]/g); <-- This gets rid of brackets and spaces

Upvotes: 3

Views: 504

Answers (3)

Sohail Ashraf
Sohail Ashraf

Reputation: 10579

try this.

let str = '+44 (0)1234 123321';
console.log(str.replace(/\(.*?\)|[^0-9+]/g, '')); 

Upvotes: 0

Michael Bianconi
Michael Bianconi

Reputation: 5242

let string = '+44 (0)1234 123321';
let regex = /\s+|\(.*?\)/g;
let result = string.replace(regex,'');

\s+ matches any whitespace. \(.*\) matches anything inside of parenthesis.

Upvotes: 2

Felipe N Moura
Felipe N Moura

Reputation: 1617

What about this?

phoneRaw = '+44 (0)1234 123321';

function clearPhoneNumber (phone) {
  return phoneRaw.replace(/(\(\d+\))|[^\d]/g, '');
}

clearPhoneNumber(phoneRaw);

It will replace anything in between (...) and anything that isn't a number.

If you want to keep the + sign, you can use this instead, inside that function:

return phoneRaw.replace(/(\(\d+\))|[^\d|\+]/g, '');

Upvotes: 0

Related Questions