微信小程序-利用wxs脚本实现姓名、手机号、身份证号中间带星显示

WXS(WeiXin Script)是小程序的一套脚本语言,结合 WXML,可以构建出页面的结构。WXS 与 JavaScript 是不同的语言,有自己的语法,并不和 JavaScript 一致。详情可见.

首先,我们可以和pages同级之下创建一个wxs文件夹,所有的wxs文件都可以存放在该目录下。

1.创建subutil.wxs

在subutil.wxs中新建一个sub方法,根据特定需求截取字符串,并显示为带 * 号的字符串(前startLength位 + 自定义* 号 + 后endLength位),如果字符串长度小于startLength + endLength,则返回原始字符串:

/**
 * 处理字符串为*格式,中间显示自定义*号
 * str 需要处理的字符串
 * startLength 前面显示的字符串长度
 * endLength 后面显示的字符串长度
 */
var sub = function(str, startLength, endLength) {
  if (str.length == 0 || str == undefined) {
    return "";
  }
  var length = str.length;
  if (length >= startLength + endLength) {
    //判断当字符串长度为二时,隐藏末尾
    if (length === 2) {
      return str.substring(0, 1) + '*';
    } 
    else if (3 <= length && length <= 10){
      return str.substring(0, 1) + '**';
    }
    //判断字符串长度大于首尾字符串长度之和时,隐藏中间部分
    else if (length >= 11) {
      return str.substring(0, startLength) + "****" + str.substring(length - endLength, length);
    } else {
      return str
    }
  }
}
module.exports = {
  sub: sub
}

2.wxml引用

根据wxs文件所在的目录层级编写合理的路径,使用如下代码在wxml中引入wxs。

<!-- 引入wxs脚本 -->
<wxs src="../../wxs/subutil.wxs" module="tools" />

3.使用

在需要使用的地方使用如下代码即可:

{{tools.sub(string, x, y)}}

以上就是利用wxs实现*号隐藏数据信息的全部内容啦!

你可能感兴趣的:(微信小程序)