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:
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const letters: string[] = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'];
const replacement: string[] = ['a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z'];
let result: string = text.toLocaleLowerCase();
for (let index = 0; index < letters.length; index++) {
result = result.replaceAll(letters[index], replacement[index]);
}
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
console.log('after : ' + result); // after : wspolczynnik pochlaniania dzwieku
Warnings:
StringreplaceAll()was introduced in ES2021,StringreplaceAll()is supported by Node.js v16.
Optimal solutions
In this section, you can find solutions that have quite good computational complexity.
1. replace() function-based solution
const expression: RegExp = /[ąćęłńóśźż]/gi;
const replacements: Record<string, string> = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
};
const replacePolishLetters = (text: string): string => {
return text.replace(expression, (letter) => replacements[letter]);
};
// Usage example:
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const result: string = replacePolishLetters(text);
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
console.log('after : ' + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU
2. for loop-based solution
const expression: RegExp = /[ąćęłńóśźż]/gi;
const replacements: Record<string, string> = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
};
const replacePolishLetters = (text: string): string => {
let result = '';
for (let i = 0; i < text.length; ++i) {
const entry = text[i];
result += replacements[entry] ?? entry;
}
return result;
};
// Usage example:
const text: string = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const result: string = replacePolishLetters(text);
console.log('before: ' + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
console.log('after : ' + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU