0

I am trying to replace the +27 prefix on a South African Cell Phone number using a regular expression, please help guys.

Example:

let number = "+27712345678";
number = number.replace(/[+27]/g, "0");
console.log(number);

output is: 000010345608

All I want is to just replace the +27 with a Zero (0) and leave everything as it is.

Thanks you guys in advance.

Code Maniac
  • 33,907
  • 4
  • 28
  • 50
Cya
  • 77
  • 1
  • 8
  • 2
    `.replace(/\+27/, "0");`, assuming there are no weird spaces or other phone number specific details, which i don't know about. – ASDFGerte Sep 23 '19 at 11:35
  • 1
    Your problem is that `[+27]` matches any characters in the set `+`, `2` and `7`, **not** the sequence `+27`. That is why your output is the input with *all* of those characters replaced with `0`. @ASDFGerte comment is what you want. – Nick Sep 23 '19 at 11:38
  • @ASDFGerte Thanks a lot, this is indeed what I wanted, thank you. – Cya Sep 23 '19 at 11:52

1 Answers1

2

You need to use ^ ( start of string anchor )

 ^\+27
  • ^ - Start of string
  • \+ - Matches +
  • 27 - Matches number 27

const replacePrefix = str => str.replace(/^\+27/, '0');

console.log(replacePrefix("+27712345678"))

Note:- [+27] character class means match any of the characters specified inside character class, so here it means match either of + or 2 or 7 one time since we don't have any quantifier after character class

Code Maniac
  • 33,907
  • 4
  • 28
  • 50