Search This Blog

2024/03/21

Javascript Regular Expression:Convert indian landline number string to hypenated and bracketed

Here we will convert a indian landline number with isd + std + phone number
to hypenated phone number & bracketted phone number using regular expression.

Code:
var landline = "912367233427"
var pattern=/(\d{2})(\d{4})(\d{6})/

//hypeneted - the replace above is termed as replace with subexpression
var formattedLandline = landline.replace(pattern,"$1-$2-$3")

console.log(formattedLandline)

//bracketed
var formattedLandlineBracket = landline.replace(pattern,"(+$1) $2 $3")
console.log(formattedLandlineBracket)

Output:
91-2367-233427
(+91) 2367 233427

No comments:

Post a Comment