JS string.replace 接受正则表达式

内容分享5天前发布
0 0 0

String.prototype.replace(regexp/substr,replacement)

  • 第一个参数可以是正则表达式,
  • 但是要记得带上 /regexp/g ,大多数情况下要带上 g ,否则会让你怀疑是不是记错API了。
  • 列如,我要实现一个功能只能输入数字和小数点,其他的字符都要删除掉,就可以利用 string.replace 这个API
  • 参考: https://regex101.com/r/RfMXzg/1
  • 用下面这段代码可以达到目的

(val)=>{
  const xx = val.replace(/[^0-9.]*/g, "")
  return xx;
}

  • 但是如果去除 g 就没效果了,o(╥﹏╥)o

文档贴上:

  • https://www.w3school.com.cn/jsref/jsref_replace.asp
  • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace MDN

代码片段:

<el-input v-model="employeeData.trueSendMoney"  clearable 
  @input="check_digit_input($event,  trueSendMoney )" ></el-input>

//只能输入数字和小数点
check_digit_input(val, inputField){
  this.funcDigitOnly(val, inputField)
},

//只能输入数字和小数点
funcDigitOnly(val, target){
  // https://regex101.com/r/RfMXzg/1
  const reg = /^[0-9.]*$/
  if (!reg.test(val)) {
    const xx = val.replace(/[^0-9.]*/g, "")
    this.$set(this.employeeData, target, xx);
    //this.employeeData[target] = val.substring(0, val.length - 1)
    this.$message({ showClose: true, message:  只能输入数字和小数点! , type:  error  });
  }
},

End

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...