Skip to content

Commit 3c991cb

Browse files
committed
refactor: Improve getCountryCode function
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.
1 parent 9bcb613 commit 3c991cb

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

packages/countries/src/getCountryCode.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,14 @@ import { getCountryDataList } from './getCountryData.ts'
44
const countryDataList = getCountryDataList()
55

66
export const getCountryCode = (countryName: string): TCountryCode | false => {
7+
// Escape special RegExp characters
8+
const name = `${countryName}`
9+
.trim()
10+
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
11+
.replace(/-/g, '\\x2d')
12+
713
// Match exact country name, but case insensitive
8-
const nameRegex = new RegExp('^' + countryName + '$', 'i')
14+
const nameRegex = new RegExp('^' + name + '$', 'i')
915

1016
return (
1117
countryDataList.find(({ name, native }) => nameRegex.test(name) || nameRegex.test(native))

packages/test-node/getCountryCode.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,15 @@ test('getCountryCode()', () => {
1212
assert.equal(getCountryCode('Ukrain'), false)
1313
assert.equal(getCountryCode('Ukraine1'), false)
1414
assert.equal(getCountryCode('Unknown'), false)
15+
16+
// Should not care about leading/trailing spaces
17+
assert.equal(getCountryCode(' Ukraine '), 'UA')
18+
19+
// More unicode tests
20+
assert.equal(getCountryCode('မြန်မာ'), 'MM')
21+
assert.equal(getCountryCode('澳門'), 'MO')
22+
23+
// Special symbols
24+
assert.equal(getCountryCode('Myanmar (Burma)'), 'MM')
25+
assert.equal(getCountryCode('Cocos (Keeling) Islands'), 'CC')
1526
})

0 commit comments

Comments
 (0)