前端常见需求整理 - 表单相关(脱敏、根据字节限制)

用户名脱敏

两个字,则脱敏第二个字

三个字,则脱敏第二个字

三字以上,则脱敏第二和第三个字

// 用户名脱敏
export const treatName = function (str) {
    
    
  if (str.length == 2) {
    
    
    return str.substring(0, 1) + '*'
  } else if (str.length == 3) {
    
    
    return str.substring(0, 1) + "*" + str.substring(2, 3)
  } else if (str.length > 3) {
    
    
    return str.substring(0, 1) + "*" + '*' + str.substring(3, str.length)
  }
  return ''
}

限制输入的字节数

代码示例场景为 vue3

<input @input="handleInput" v-model="inputValue"/>

const inputValue = ref('')
function getStr(str, num){
  let len = 0;
  const chinese = /[^\x00-\xff]/ig;
  for(let i=0;i<str.length;i++){
    if(str.charAt(i).match(chinese)){
      len +=2;
    }else{
      len +=1;
    }
    if(len > num){
      return str.slice(0,i)
    }
  }
  return str
}
function handleInput(){
  inputValue.value = getStr(inputValue.value, 20)
}

补充的话

仓库,还提供了许多前端常见需求及实现的归纳整理,欢迎客官看看~

如果这篇笔记能够帮助到你,请帮忙在 github 上点亮 star,感谢!

猜你喜欢

转载自blog.csdn.net/qq_61270298/article/details/129807221