EN
TypeScript - replace Polish letters with English letters in a sentence
0 points
In this short article, we would like to show how to replace Polish letters with English letters in a sentence using TypeScript.
Quick solution:
xxxxxxxxxx
1
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
2
3
const letters: string[] = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'];
4
const replacement: string[] = ['a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z'];
5
6
let result: string = text.toLocaleLowerCase();
7
8
for (let index = 0; index < letters.length; index++) {
9
result = result.replaceAll(letters[index], replacement[index]);
10
}
11
12
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
13
console.log('after : ' + result); // after : wspolczynnik pochlaniania dzwieku
Warnings:
String
replaceAll()
was introduced in ES2021,String
replaceAll()
is supported by Node.js v16.
In this section, you can find solutions that have quite good computational complexity.
xxxxxxxxxx
1
const expression: RegExp = /[ąćęłńóśźż]/gi;
2
3
const replacements: Record<string, string> = {
4
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
5
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
6
};
7
8
const replacePolishLetters = (text: string): string => {
9
return text.replace(expression, (letter) => replacements[letter]);
10
};
11
12
13
// Usage example:
14
15
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
16
const result: string = replacePolishLetters(text);
17
18
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
19
console.log('after : ' + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU
xxxxxxxxxx
1
const expression: RegExp = /[ąćęłńóśźż]/gi;
2
3
const replacements: Record<string, string> = {
4
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
5
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
6
};
7
8
const replacePolishLetters = (text: string): string => {
9
let result = '';
10
for (let i = 0; i < text.length; ++i) {
11
const entry = text[i];
12
result += replacements[entry] ?? entry;
13
}
14
return result;
15
};
16
17
18
// Usage example:
19
20
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
21
const result: string = replacePolishLetters(text);
22
23
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
24
console.log('after : ' + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU