You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否有React JS库可获取系统语言并返回'en'格式的语言代码?

How to Get System Language Code (e.g., 'en') in React JS

Hey there! It looks like you’ve been reaching for Node.js-focused libraries like os-locale or os in your React app—those tools are built for server-side/Node environments, not the browser where React runs. That’s why they weren’t working for you! Let’s use browser-native APIs instead, which are designed exactly for this frontend use case.

Method 1: Use navigator.language (Simplest Approach)

The navigator.language property returns the browser’s default language, which almost always matches the user’s system language. We can split the full locale string (like en-US or en-GB) to get just the 2-letter code:

const getSystemLanguageCode = () => {
  // Extract the first part of the locale (e.g., 'en' from 'en-US')
  const languageCode = navigator.language.split('-')[0];
  // Return 'en' specifically if it's an English variant
  return languageCode === 'en' ? 'en' : languageCode;
};

// Use it in your React component
function LanguageDetector() {
  const systemLangCode = getSystemLanguageCode();
  return (
    <div>
      Detected system language code: <strong>{systemLangCode}</strong>
    </div>
  );
}

Method 2: Use navigator.languages (For Multiple Language Preferences)

If you want to account for the user’s full list of preferred languages (set in browser settings), navigator.languages gives you an array of their language priorities. We’ll grab the first entry (the highest priority) and extract the code:

const getPreferredLanguageCode = () => {
  // Check if the languages array is available
  if (navigator.languages && navigator.languages.length > 0) {
    return navigator.languages[0].split('-')[0];
  }
  // Fallback to navigator.language if the array isn't supported
  return navigator.language.split('-')[0];
};

Key Notes to Know

  • Browser vs. System Language: These APIs return the browser’s configured language, which is usually inherited from the user’s system. If a user manually changes their browser language, it will return that instead of the system language—this is a frontend security/privacy limitation, as browsers can’t directly access system-level settings.
  • Why Your Previous Libraries Failed: os-locale and os interact directly with the operating system, which only works in Node.js (server-side) or desktop frameworks like Electron (in the main process). React runs in the browser sandbox, so those tools can’t access system-level data.

内容的提问来源于stack exchange,提问作者Jathin jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:42