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;
相关推荐
孟陬1 小时前
Foobar 技术周刊#159:当看不懂代码时,如何高效排障调试。脏页陷阱:一条只读查询,写入数 TB 数据。推测解码:大模型加速利器
前端·人工智能·后端
Zhao-Jichao1 小时前
AI Prompting for Everyone 课程笔记 - P17 图像生成 Imaging Generation
前端
Highcharts.js2 小时前
智能数据分析组件Orbit 正式发布与快速上手体验教程
前端·人工智能·信息可视化·数据分析系统·highcharts·orbit·智能可视化
螺丝钉tina2 小时前
[Playwright ][16]Playwright + TypeScript API 自动化测试实战:API测试
前端·javascript·typescript
小天源3 小时前
智叟云集系统 · 架构与职责分层
服务器·前端·数据库
Highcharts.js5 小时前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
薛定谔的猫-菜鸟程序员5 小时前
Electron开发超详细教程(从入门到放弃)
前端·javascript·electron
最强小杰5 小时前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
静水leo6 小时前
使用 Whistle 拦截接口并模拟后端响应
前端
掘金者阿豪6 小时前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?
前端·后端