EN
JavaScript - replace Polish letters with English letters in a sentence
7
points
In this short article, we would like to show how to replace Polish letters with English letters in a sentence using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const letters = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'];
const replacement = ['a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z'];
let result = text.toLocaleLowerCase();
for (let i = 0; i < letters.length; ++i) {
result = result.replaceAll(letters[i], replacement[i]);
}
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 less computational complexity.
1. replace() function-based solution
// ONLINE-RUNNER:browser;
const expression = /[ąćęłńóśźż]/gi;
const replacements = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
};
const replacePolishLetters = (text) => {
return text.replace(expression, (letter) => replacements[letter]);
};
// Usage example:
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const result = 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
// ONLINE-RUNNER:browser;
const replacements = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
};
const replacePolishLetters = (text) => {
let result = '';
for (let i = 0; i < text.length; ++i) {
const entry = text[i];
result += replacements[entry] ?? entry;
}
return result;
};
// Usage example:
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
const result = replacePolishLetters(text);
console.log("before: " + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
console.log("after : " + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU