Languages

Javascript - how to replace all character that is not a letter or number with underscore and also replace Polish letters with English letters

5 points
Asked by:
Krzysiek
741

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
Answered by:
Krzysiek
741

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join