Skip to content

Regex: remove everything except the letters and separator

I am currently using replace statements to replace certain parts of a string. I think my code is a bit over the top and could be simplified:

const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5'
locales = locales.replace('-','_')
locales = locales.replace(';q=','')
locales = locales.replace(/[0-9]/g,'')
locales = locales.replace('.','')

In the end, I want to remove everything except for the locale from the string using regex and replace - with _. I would like the final string to look like this:

'fr_CH, fr, en, de, *'



A carefully chosen regular expression can strip out the weightings in one replacement. A second switches the hyphens - for underscores _

const locales = 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5';
newLocales = locales.replace(/;q=d*.d*/g,'').replace(/-/g,'_');
console.log(newLocales);   //  fr_CH, fr, en, de, *