React Native js常用字符输入处理方法

1.过滤表情

// 过滤表情
const dealEmojion = (text) => {
  const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
  return text.replace(regStr, '');
};

2.单行输入框限度最多输入20个字符。要去掉所有空格。

const singleInput = (text) => {
const newText = dealEmojion(text).split(" ").join("");
if(newText.length > 20) {
  return newText.substr(0,20);
}
return newText;
};

3.多行输入框限度最多输入300个字符。去掉首尾空格。

const multiLineInput = (text) => {
 const newText = dealEmojion(text).trim();
 if(newText.length > 300) {
   return newText.substr(0,300);
 }
 return newText;
};

4.只能输入数字

// 只能输入数字
const onlyInputNum = (num) => num.replace(/[^\d]/g,'');

5.数字输入框 数字输入框整数位<=9位,小数点两位

// 数字输入框 数字输入框整数位<=9位,小数点两位。
const numInput = (text) => {
  let mText = text.replace(/[^\d.]/g,"");
      mText = mText.replace(/\.{2,}/g,".");
      mText = mText.replace(/^\./g,"");
      mText = mText.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
      mText = mText.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
      let relStr = "0";
      if(mText.toString().indexOf(".") != -1 ) {
        const newArr = mText.split(".");
        if(newArr[1].length>0) {
          relStr = `${(newArr[0].substr(0,9))}.${newArr[1]}`;
        }else{
          relStr = mText;
        }
      }else{
        relStr = mText.substr(0,9);
      }
      return relStr.toString();
};
  1. 末尾为点数字的转化成小数
// 末尾为点的转化成小数
const dealEndPointNum = (text) => parseFloat(text);

7.支持可输入n个字符,即字母和数字可输入n个,汉字算2个

// 字符长度输入验证
const inputFormatValide = (text,maxLength) => {
    // 去掉空格
    const newText =  text.split(" ").join("");
    // 获取字符长度
    let len = 0;
    for(let i=0;i maxLength) {
        if(isHanzi(newText.charAt(newText.length-1))&&len!=maxLength+1){
            return newText.substr(0,newText.length-len+maxLength+1);
        }else{
            return newText.substr(0,newText.length-len+maxLength);
        }
    }
    return newText;
};

// 验证是否是汉字
const isHanzi = (text) => {
    return text.match(/[^\x00-\xff]/ig) != null;
};

你可能感兴趣的:(React Native js常用字符输入处理方法)