简体   繁体   中英

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

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

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

try this.

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

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, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM