javascript 国コードから国名を取得する
- 作成日 2022.10.30
- javascript
- javascript
javascriptで、国コードから国名を取得するサンプルコードを記述してます。「Intl.DisplayNames」を使用することで可能です。取得できる国名の表示言語も設定することができます。簡単なサンプルコードはページに下部にあります。
環境
- OS windows11 pro 64bit
- ブラウザ chrome 107.0.5304.63
国コードから国名を取得
国コードから国名を取得するには、
1. 国際化表示名を取得できる「Intl.DisplayNames」を生成
2.「ロケール」を「ja」に「オプション」で「type」を「地域(region)」に設定
3. 「of」を使用して対象の国コードを引数に指定
することで可能です。
const result = new Intl.DisplayNames(
['ja'], {type: 'region'}
);
// ofで表示名取得
console.log(result.of('JP')); // 日本
console.log(result.of('US')); // アメリカ合衆国
console.log(result.of('AU')); // オーストラリア
console.log(result.of('GB')); // イギリス
console.log(result.of('TW')); // 台湾
「local」を英語に指定すると、英語で取得されます。
※指定できる地域はこちらで確認できます。
const result = new Intl.DisplayNames(
['en'], {type: 'region'}
);
// ofで表示名取得
console.log(result.of('JP')); // Japan
console.log(result.of('US')); // United States
console.log(result.of('AU')); // Australia
console.log(result.of('GB')); // United Kingdom
console.log(result.of('TW')); // Taiwan
type
「type」に指定できる値には、以下のものがあります。
'calendar':暦
'currency':通貨
'dateTimeField':日時フィールド
'language':言語
'region':地域
'script':文字体系
例えば「dateTimeField」を指定すると日本語で以下の結果が返ります。
const result = new Intl.DisplayNames(
['ja'], {type: 'dateTimeField'}
);
// ofで表示名取得
console.log(result.of('year')); // 年
console.log(result.of('quarter')); // 四半期
console.log(result.of('month')); // 月
console.log(result.of('weekOfYear')); // 週
console.log(result.of('weekday')); // 曜日
console.log(result.of('day')); // 日
「currency」を設定すると以下の結果が返ります。
const result = new Intl.DisplayNames(
['ja'], {type: 'currency'}
);
// ofで表示名取得
console.log(result.of('JPY')); // 日本円
console.log(result.of('USD')); // 米ドル
console.log(result.of('EUR')); // ユーロ
console.log(result.of('GBP')); // 英国ポンド
console.log(result.of('SGD')); // シンガポール ドル
サンプルコード
以下は、
「取得」ボタンをクリックすると、フォームに入力された国コードから国名を取得した結果を表示するサンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-50" style="margin-top:200px">
<h2><span class="badge badge-danger">結果</span></h2>
<form>
<div class="form-group">
<input type="text" id="setData">
</div>
</form>
<button type="button" onclick="seachFirstNum()" class="btn btn-danger mt-1">
取得
</button>
</div>
<script>
const seachFirstNum = () => {
let elm = document.getElementsByClassName("badge")[0];
elm.textContent = new Intl.DisplayNames(['ja'], {type: 'region'}).of(setData.value);
}
</script>
</body>
</html>
結果が表示されていることが確認できます。
-
前の記事
Dart リスト(配列)の指定した位置に値を挿入する 2022.10.30
-
次の記事
ubuntu アプリの検索を表示するショートカットキー 2022.10.30
コメントを書く