0

I first check the navigator.languages array for its first element.

Then I get either navigator.userLanguage or navigator.language.

If this fails we get navigator.browserLanguage.

const getNavigatorLanguage = () =>
  (navigator.languages && navigator.languages.length) ?
    navigator.languages[0] :
    navigator.userLanguage ||
      navigator.language ||
      navigator.browserLanguage 

I can get the result depending on the location in the format: en-US, fr-FR, pl-PL, es-ES. Is it possible to get the result in the format: en, fr, pl, es?
Without US,FR, PL,ES

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Umbro
  • 1,984
  • 12
  • 40
  • 99

1 Answers1

1

You have basically three ways to do this. Split on a hyphen - and get the first element of the array:

const [res] = getNavigatorLanguage().split("-");

Use a regex:

const [, res] = getNavigatorLanguage().match(/(\w*?)-/);

Or use substring:

const res = getNavigatorLanguage.substring(0, 2);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79