Skip to content

Commit

Permalink
refactor: Improve getCountryCode function
Browse files Browse the repository at this point in the history
Refactor the getCountryCode function to handle special characters and symbols in country names. This ensures that the function can match country names accurately, even when they contain special characters or symbols. The function now escapes special RegExp characters and replaces hyphens with the appropriate escape sequence. Additionally, the function now trims leading and trailing spaces from the country name before matching it against the country data list.
  • Loading branch information
dmythro committed Jul 31, 2024
1 parent 9bcb613 commit 3c991cb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/countries/src/getCountryCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import { getCountryDataList } from './getCountryData.ts'
const countryDataList = getCountryDataList()

export const getCountryCode = (countryName: string): TCountryCode | false => {
// Escape special RegExp characters
const name = `${countryName}`
.trim()
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d')

// Match exact country name, but case insensitive
const nameRegex = new RegExp('^' + countryName + '$', 'i')
const nameRegex = new RegExp('^' + name + '$', 'i')

return (
countryDataList.find(({ name, native }) => nameRegex.test(name) || nameRegex.test(native))
Expand Down
11 changes: 11 additions & 0 deletions packages/test-node/getCountryCode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,15 @@ test('getCountryCode()', () => {
assert.equal(getCountryCode('Ukrain'), false)
assert.equal(getCountryCode('Ukraine1'), false)
assert.equal(getCountryCode('Unknown'), false)

// Should not care about leading/trailing spaces
assert.equal(getCountryCode(' Ukraine '), 'UA')

// More unicode tests
assert.equal(getCountryCode('မြန်မာ'), 'MM')
assert.equal(getCountryCode('澳門'), 'MO')

// Special symbols
assert.equal(getCountryCode('Myanmar (Burma)'), 'MM')
assert.equal(getCountryCode('Cocos (Keeling) Islands'), 'CC')
})

0 comments on commit 3c991cb

Please sign in to comment.