Search code examples
javascriptlodash

String matches with prefixes


I am new to Javascript. Suppose,I have a contact number and array of prefixes which are string.

contactNumber = "0204221246890";
prefixes = ["027", "020", "021", "022", "028", "029", "0204", "03", "04", "06", "07", "09"];

So the logic is I need to loop through prefixes and

 if (contactNumber.startsWith(prefix)) {
         contactNumberPrefix = prefix
         contactNumberNumber = contactNumber.substring(lineNumberPrefix.length);

       }

How to best achieve this is through lodash or javascript ?


Solution

  • You can utilize Array#some to loop through the available prefixes. It returns true if any one of the matches are true. See the demo below:

    let contactNumber = "0204221246890";
    let prefixes = ["027", "020", "021", "022", "028", "029", "0204", "03", "04", "06", "07", "09"];
    
    if (prefixes.some(prefix => contactNumber.startsWith(prefix))) {
      console.log('matches');
    }

    Edit 1:

    If you need to return the matching prefix, its better to use Array#find instead. It returns the first matching item from the array.

    let prefix = prefixes.find(prefix => contactNumber.startsWith(prefix));
    return [contactNumber, prefix];
    

    This will return the matching prefix and the contact number to the caller, which you can destructure.