> 文档中心 > OpenHarmony工具集之字符串工具·让代码更精简

OpenHarmony工具集之字符串工具·让代码更精简


介绍

字符串处理是应用程序中最常见的,比如用户账号输入是否为空,用户账号是否数字字母组合,用户password是否数字、字母、特殊符号组合等。如果每个字符串验证的地方都去写,代码量大且不易维护,将共用性强的抽离成方法,统一调用则会使代码更健壮。

准备知识

  • replace() 替换字符串中的字符为其他字符
  • substr() 从指定开始位置截取字符串到指定结束位置
  • 正则表达式

封装方法

  • isEmpty(str: string) 是否为空
  • isNotEmpty(str: string) 不为空
  • isAnyEmpty(...strArr: any) 存在空
  • isNoneEmpty(...strArr: any) 所有值不为空
  • isBlank(str: string) 是否为真空(和isEmpty区别在于空格的判断
  • isNotBlank(str: string)不为真空
  • isAnyBlank(...strArr: any) 存在真空
  • isNoneBlank(...strArr: any) 所有值不为真空
  • isAlpha(str: string) 只包含字母
  • isAlphaSpace(str: string) 只包含字母、空格
  • isAlphanumeric(str: string) 只包含字母、数字
  • isAlphanumericSpace(str: string) 只包含字母、数字和空格
  • isNumeric(str: string)数字
  • isSpecialCharacterAlphanumeric(str: string) 只包含特殊字符、数字和字母
  • removePrefix(str: string, prefix: string)移除指定前缀
  • removeSuffix(str: string) 移除文件后缀

使用方法

在具体页面引入StrUtil

import str from '@ohos/tecore/src/main/ets/utils/StrUtil';

需要调用字符串处理方法的地方,调用需要的方法即可。如下代码实现移除文件后缀名:

@Entry@Componentstruct StrUtil {  @State text: string = "";  @State realStr: string = "";  controller: TextInputController = new TextInputController();  build() {    Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center}) {      Text(`移除后缀: ${this.realStr}`) .fontSize(18).fontWeight(FontWeight.Bold)      TextInput({placeholder: '请输入...', controller: this.controller}) .onChange((value) => {   this.text = value; })      Button('验证') .width(200).height(64) .fontSize(18).fontWeight(FontWeight.Bold) .onClick(() => {   this.realStr = str.removeSuffix(this.text).toString(); })    }    .width('100%')    .height('100%')  }}

OpenHarmony工具集之字符串工具·让代码更精简

说明

暂且提供了一些常用且简单的方法,后续会对其进行扩展。