Skip to content

Instantly share code, notes, and snippets.

@abdulloooh
Last active March 1, 2021 15:03
Show Gist options
  • Save abdulloooh/36b1f49bef27427c26ef05f60f4ea428 to your computer and use it in GitHub Desktop.
Save abdulloooh/36b1f49bef27427c26ef05f60f4ea428 to your computer and use it in GitHub Desktop.
FORMAT ALL VARIANTS OF WRITING NIGERIA NUMBER (+234**, 234**, 0**, ** ) TO COMMON 0**

line 2 and 3 First check if the number starts with either 234 or +234 using regex stored inside pattern

block 4 If it contains (+)234, check if there is + and replace it with empty string, then replace 234 with 0

If the number did not contain (+)234, the if block in line 4 is skipped to line 8

Number now must have been stripped of 234 or +234 and replaced with 0

But what if the number did not contain 234 or +234 or even 0 e.g 9036051122

So

line 8 Check for the 0 is not present at all, then add 0

line 9 return desired value e.g 09033221100

function format(number) {
const pattern = /^(234|\+234)/
const contains234 = pattern.test(number)
if (contains234) {
if (number.indexOf("+") === 0) number = number.replace("+", "")
number = number.replace("234", "0")
}
if (number.indexOf("0") !== 0) number = "0" + number
return number
}
//Test
format("+2349033221100") //"09033221100"
format("2349033221100") //"09033221100"
format("09033221100") //"09033221100"
format("9033221100") //"09033221100"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment