javascript - 从 React 中的 Cookie 获取电话号码前缀
问题描述
我知道我们可以用这个方法得到一个国家的iso代码:
import Cookies from 'js-cookie';
const iso = Cookies.get('CK_ISO_CODE');
console.log(iso); // -> 'us'
有没有办法获取电话前缀?
例如,对于美国,它应该是 +1,对于 FR +33 等等。
解决方案
你会想要使用这个 npm 包:https ://www.npmjs.com/package/world-countries
首先,这是一个在片段中工作的示例。我们必须获取 JSON 文件,以便 eventListener 是异步的,但如果您使用 npm 包(下一个示例),它不必是异步的。
document.querySelector("#load-prefix").addEventListener("click", async () => {
const world = await fetch(`https://cdn.jsdelivr.net/npm/world-countries@4.0.0/countries.json`).then(res => res.json())
const iso = document.querySelector("#iso").value;
const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
const phonePrefixStart = country ? country.idd.root : "unknown";
const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
const phonePrefix = phonePrefixStart + phonePrefixEnd;
document.querySelector("#output").innerText = phonePrefix;
});
<input placeholder="iso code" id="iso" />
<button id="load-prefix">Get Phone Prefix</button>
<p id="output"></p>
使用 npm 包,它看起来像这样。(此示例不起作用,因为 Stack Snippets 不包含模块捆绑器)
const world = require('world-countries')
// or
import world from "world-countries";
document.querySelector("#load-prefix").addEventListener("click", () => {
const iso = document.querySelector("#iso").value;
const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
const phonePrefixStart = country ? country.idd.root : "unknown";
const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
const phonePrefix = phonePrefixStart + phonePrefixEnd;
document.querySelector("#output").innerText = phonePrefix;
});
<input placeholder="iso code" id="iso" />
<button id="load-prefix">Get Phone Prefix</button>
<p id="output"></p>
所以回到你的问题,它看起来像这样:
import Cookies from 'js-cookie';
import world from "world-countries";
const iso = Cookies.get('CK_ISO_CODE');
console.log(iso); // -> 'us'
const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
const phonePrefixStart = country ? country.idd.root : "unknown";
const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
const phonePrefix = phonePrefixStart + phonePrefixEnd;
console.log(phonePrefix); // -> '+1'
推荐阅读
- hadoop - HDFS 和 ADLS 有什么区别?
- python - Python 数据操作 - pd.apply
- sql - case when 与 if else 语句
- python-3.x - 当我们需要在 exec() 函数中指定数据类型时?
- json - 在 telegraf.conf 中将 JSON 值解析为单独的字符串
- rust - 我可以用迭代器做到这一点吗?
- javascript - Vuex - 两次转换存储项目,提交新项目,或者每次安装都在组件中进行转换?
- python - 在 Pandas 列中选择具有中间值的行
- docker - 从 docker 导入本地环境中的模块
- c# - 查询中 GroupBy 方法的自定义比较