RN传入数字返回拼音首字母的包

安装包 yarn add pinyin@^3.0.1 我当前项目的版本

切记不要安装4.0.0-alpha.0 这种版本号后面带字母的,会有问题

js 复制代码
import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import {pinyin} from 'pinyin';

const App = () => {
  // 定义一个函数来将汉字转为拼音并返回首字母
  const getFirstLetter = chineseChar => {
    // 使用 pinyin 库将汉字转为拼音数组
    const pinyinArray = pinyin(chineseChar, {
      style: pinyin.STYLE_FIRST_LETTER, // 使用首字母风格
    });
    // 如果转换成功,返回首字母;否则返回原字符(如果是英文的话已经被转换为大写了)
    return pinyinArray.length > 0
      ? pinyinArray[0][0].toUpperCase()
      : chineseChar;
  };
  // 测试函数
  const test = () => {
    const chineseChar = '你好';
    const chineseChar1 = 'a你好';
    const chineseChar2 = 'a你好';
    const chineseChar3 = 'a你a好a';
    const chineseChar4 = '你a好a';
    const chineseChar5 = '你a好';
    const chineseChar6 = '你好a';
    const chineseChar7 = 'abc';
    const chineseChar8 = '?,/';
    const firstLetter = getFirstLetter(chineseChar);
    const firstLetter1 = getFirstLetter(chineseChar1);
    const firstLetter2 = getFirstLetter(chineseChar2);
    const firstLetter3 = getFirstLetter(chineseChar3);
    const firstLetter4 = getFirstLetter(chineseChar4);
    const firstLetter5 = getFirstLetter(chineseChar5);
    const firstLetter6 = getFirstLetter(chineseChar6);
    const firstLetter7 = getFirstLetter(chineseChar7);
    const firstLetter8 = getFirstLetter(chineseChar8);
    // 上面那个函数将包含中文的直接转换后返回首字母,非中文的如果是英文则转换为大写直接返回,特殊字符也是直接返回
    console.log(firstLetter); // 输出:N
    console.log(firstLetter1); // 输出:A
    console.log(firstLetter2); // 输出:A
    console.log(firstLetter3); // 输出:A
    console.log(firstLetter4); // 输出:N
    console.log(firstLetter5); // 输出:N
    console.log(firstLetter6); // 输出:N
    console.log(firstLetter7); // 输出:ABC
    console.log(firstLetter8); // 输出:?
  };

  // 调用测试函数
  test();
  return (
    <View>
      <Text>111</Text>
    </View>
  );
};

export default App;
相关推荐
di24k24k13 分钟前
多个 el-form 共用同一 ref 导致表单校验部分失效
前端·javascript·vue.js·elementui
NutShell Wang24 分钟前
每帧重建整条路径、每秒倾倒 48MB 给 GC:实时折线图渲染架构的实测复盘
前端·性能优化·架构·图形渲染·数据可视化·vibe coding
小彤花园43 分钟前
和 AI 结对写网站:从 JSON 到一整个工具集
前端·人工智能·程序员
RD_daoyi1 小时前
Google核心算法不再通知!全年持续滚动更新
大数据·服务器·前端·网络·搜索引擎·.net
এ慕ོ冬℘゜1 小时前
纯 CSS 实现自定义 Switch 开关(商品上下架滑块)
前端·css
再吃一根胡萝卜1 小时前
dompdf.js 分页功能完整实现指南
前端
wordbaby1 小时前
App 热更新(OTA)原理深解 —— 以 React Native 为例
前端·react native
再吃一根胡萝卜1 小时前
Vue + dompdf.js 实现简历分页导出的完整踩坑记录
前端
其美杰布-富贵-李2 小时前
第 6 篇:相机与 OrbitControls
前端·javascript·three.js
lichenyang4532 小时前
从图片生成任务到用户隔离:AIGC Creative Studio 后端与 PostgreSQL 建模实践
前端·后端