DEV Community

Tonny Kirwa
Tonny Kirwa

Posted on

Formatting Phone Number in JavaScript - Country Code + Leading Zero (0)

To ensure that smsPhone is in the format '+2547XXXXXXXX', you can modify the code as follows:

// Assuming smsPhone is a variable holding the phone number
const formattedPhone = `+${smsPhone.replace(/^0/, '254')}`;

const response = await sms.send({
    to: [formattedPhone],
    message: smsMessage,
    enqueue: true
});
Enter fullscreen mode Exit fullscreen mode

This code uses the replace function to replace the leading '0' in the phone number with '254' and then adds a '+' to the beginning. This ensures that the phone number is in the international format. Ensure that smsPhone is a string representing the phone number without the country code. The modified formattedPhone variable should then be used in the to field of the sms.send method.

Top comments (0)