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

安装包
yarn add pinyin@^3.0.1 我当前项目的版本
切记不要安装4.0.0-alpha.0 这种版本号后面带字母的,会有问题

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. RN传入数字返回拼音字母

    2024-04-28 21:56:02       13 阅读
  2. 4k stars! 如何实现按拼音字母查询证券代码?

    2024-04-28 21:56:02       19 阅读
  3. Python按字母顺序返回字典键和值

    2024-04-28 21:56:02       44 阅读
  4. iOS 字符串中字母大小写转换、字母大写转换

    2024-04-28 21:56:02       31 阅读
  5. 字符判断(数字&字母

    2024-04-28 21:56:02       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-28 21:56:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-28 21:56:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-28 21:56:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-28 21:56:02       20 阅读

热门阅读

  1. go语言数据类型转换

    2024-04-28 21:56:02       12 阅读
  2. Python爱心代码

    2024-04-28 21:56:02       11 阅读
  3. next.js v14 从入门到跑路

    2024-04-28 21:56:02       11 阅读
  4. sci高效神器介绍第一站Overleaf!

    2024-04-28 21:56:02       12 阅读
  5. 微博博文爬取

    2024-04-28 21:56:02       11 阅读
  6. 【PHP】sign加签方法示例

    2024-04-28 21:56:02       13 阅读
  7. ROS2 ZEDX UBUNTU 环境配置

    2024-04-28 21:56:02       10 阅读
  8. CUDA执行模型

    2024-04-28 21:56:02       11 阅读
  9. 【mui.min.js】

    2024-04-28 21:56:02       12 阅读