后台從接口請求回來的城市相關的數據只有城市名稱,沒有排序,鋪頁面的時候要排序就很麻煩;
面向百度編程時候找到了一個包,用它來將字符串轉成拼音,就可以通過字符串截取取出拼音首字母,這樣就可以進行首字母排序了。
這個包的名字叫js-pinyin。
npm i js-pinyin
//安裝拼音庫
import pyjs from 'js-pinyin'
//引入依賴包
pyjs.getFullChars(item.name)
//獲取字符串全部拼音,並且首字母大寫;
toLocaleLowerCase().slice(0, 1)
//全部轉化成小寫,並取首字母
- getFullChars():獲取字符串全部拼音,並且首字母大寫;
- getCamelChars() : 獲取字符串拼音首字母,並大寫;
案例
pinyin.setOptions({checkPolyphone: false, charCase: 0});
console.log(pinyin.getFullChars('管理員')); //GuanLiYuan
console.log(pinyin.getCamelChars('管理員')); //GLY
console.log(pinyin.getCamelChars('1234')); //1234
console.log(pinyin.getCamelChars('english')); //english