Countries icon indicating copy to clipboard operation
Countries copied to clipboard

getCountryCode may not return for some valid countries

Open dezull opened this issue 2 years ago • 0 comments

Use case for the feature

For example, getCountryCode("Cocos (Keeling) Islands") won't return the correct country code, because of the parentheses in the country name.

Examples or links

The countryName used in the RegExp in the function is not escaped, so characters such as parentheses are interpreted as special characters:

const nameRegex = new RegExp('^' + countryName + '$', 'i')

The solution in https://github.com/annexare/Countries/issues/131 can fix this, or a slight modification:

export const getCountryCode = (countryName: string): TCountryCode | false => {
  // Match exact country name, but case insensitive
  const country = countryName.toLowerCase();

  return (
    countryDataList.find(({ name, native }) =>
       country === name.toLowerCase() ||
       country === native.toLowerCase()
    )?.iso2 || false
  )
}

Maybe allowing something like "Cocos Islands" or "Keeling Islands" also makes sense?

dezull avatar Mar 21 '24 21:03 dezull