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:
xxxxxxxxxx
1
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
2
3
const letters = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'];
4
const replacement = ['a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z'];
5
6
let result = text.toLocaleLowerCase();
7
8
for (let i = 0; i < letters.length; ++i) {
9
result = result.replaceAll(letters[i], replacement[i]);
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 less computational complexity.
xxxxxxxxxx
1
const expression = /[ąćęłńóśźż]/gi;
2
3
const replacements = {
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) => {
9
return text.replace(expression, (letter) => replacements[letter]);
10
};
11
12
13
// Usage example:
14
15
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
16
const result = 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 replacements = {
2
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
3
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
4
};
5
6
const replacePolishLetters = (text) => {
7
let result = '';
8
for (let i = 0; i < text.length; ++i) {
9
const entry = text[i];
10
result += replacements[entry] ?? entry;
11
}
12
return result;
13
};
14
15
16
// Usage example:
17
18
const text = 'WSPÓŁCZYNNIK pochłaniania DŹWIĘKU';
19
const result = replacePolishLetters(text);
20
21
console.log("before: " + text); // before: WSPÓŁCZYNNIK pochłaniania DŹWIĘKU
22
console.log("after : " + result); // after : WSPOLCZYNNIK pochlaniania DZWIEKU