0

I forgot to mention one more space after 100

i have this string phone="+46 (0) 100 234567" and i want to get the same number without (0) and the spaces.(in javascript)

final: phone = "+46100234567"

what i have tried so far is this:

  1. phone.replace(/[(0)]*[^0-9+]/g, '', '') => which erases all 0's
  2. phone.replace(/\(0\)\s*/g,'') => which erases (0) but keeps the spaces.

any help would be welcome.

Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
  • `[(0)]` means _any character_ of `(`, `0` or `)`. Please use [Regex101](https://regex101.com/) and read [Reference - What does this regex mean?](https://stackoverflow.com/q/22937618/4642212). Your second regex already erases the space after `(0)`. So put another `\s*` before it. – Sebastian Simon Feb 01 '18 at 10:36

4 Answers4

1

Use this regex:

\s+|\(\d*\)

Replace the matches with a blank string

Click for Demo

Explanation:

  • \s+ - matches 1+ occurrences of a whitespace
  • | - OR
  • \(\d*\) - matches a ( followed by 0+ digits followed by )

CODE

const regex = /\s+|\(\d*\)/g;
const str = `+46 (0) 100 234567`;
const subst = ``;

const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
  • @Jan You have a valid point but if the test string is like `+46 () 100234567`, in that case `*` would work too. I know, this is not realistic scenario but still is handled. – Gurmanjot Singh Feb 01 '18 at 10:42
1

console.info("+46 (0) 100 234567".replace(/\(0\)|\s/g, ''));

One solution is "+46 (0) 100 234567".replace(/\(0\)|\s/g, '').
With the global attribute /g you don't need to use the *.

Jose Rui Santos
  • 15,009
  • 9
  • 58
  • 71
0

Try this expression:

/\s*\(0\)\s*/g
vadzim dvorak
  • 939
  • 6
  • 24
0

Try this:

var phone = "+46 (0) 100234567";
phone.replace(/\s*\(0\)\s*/g,'');
vpalade
  • 1,427
  • 1
  • 16
  • 20