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;
相关推荐
大橙子额3 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a4 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌414 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡6 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone6 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09016 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农6 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king7 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵8 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_8 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js