Search code examples
javascripthtmlphone-numberlibphonenumber

Issue with number-formatting


I'd like to format a phoneNumber like 2133734253 with a given country code (like "US") to national format using the libphonenumber library.

What I've found in the docs is something like:

enter image description here


Because I'm not using node.js or something else I'm just linking the js-file from https://unpkg.com/libphonenumber-js/bundle/libphonenumber-js.min.js.

Using the new libphonenumber.formatNumber()-call does not seems to work because it is return a object with absolutely no content every time. How can I fix this? How to use formatNumber() the right way?

let phonenumber = new libphonenumber.formatNumber({ 
                                      country: 'US', 
                                      phone: '2133734253' 
                                    }, 'National');
console.log(phonenumber) // should be (213) 373-4253
<script src="https://unpkg.com/libphonenumber-js/bundle/libphonenumber-js.min.js"></script>


Solution

  • According to the docs, libphonenumber is not a constructor, it just provides functions, hence remove the new keyword :

    let phonenumber = libphonenumber.formatNumber({ 
                                          country: 'US', 
                                          phone: '2133734253' 
                                        }, 'National');
    console.log(phonenumber) // should be (213) 373-4253
    <script src="https://unpkg.com/libphonenumber-js/bundle/libphonenumber-js.min.js"></script>