EN
Javascript - how to replace all character that is not a letter or number with underscore and also replace Polish letters with English letters
1
answers
5
points
I have code:
// ONLINE-RUNNER:browser;
const text = 'WSPÓŁCZYNNIK ąęć ź - pochłaniania DŹWIĘKU test ąęć';
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);
console.log("after : " + result);
My current resut:
before: WSPÓŁCZYNNIK ąęć ź - pochłaniania DŹWIĘKU test ąęć
after : wspolczynnik aec z - pochlaniania dzwieku test aec
What is the best way to make from input string the result string:
before:
WSPÓŁCZYNNIK ąęć ź - pochłaniania DŹWIĘKU test ąęć
after:
wspolczynnik_aec_z_pochlaniania_dzwieku_test_aec
I have also regex that works in notepad++
Regex:
(_)+|[^0-9A-Za-z]
Replace with:
_
1 answer
2
points
Solution:
// ONLINE-RUNNER:browser;
function replaceAllRegExp(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
let text = ' WSPÓŁCZYNNIK ąęć ź - pochłaniania DŹWIĘKU test ąęć';
let result = text.toLocaleLowerCase();
const letters = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', ' '];
const replacement = ['a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', '_'];
for (let index = 0; index < letters.length; index++) {
result = result.replaceAll(letters[index], replacement[index]);
}
result = replaceAllRegExp(result, '[^A-z0-9_]', '');
console.log("before: " + text);
console.log("after : " + result);
// before: WSPÓŁCZYNNIK ąęć ź - pochłaniania DŹWIĘKU test ąęć
// after : _wspolczynnik_aec_z__pochlaniania_dzwieku_test_aec
See also
0 comments
Add comment