根据数据动态屏蔽输入

问题描述

我有一个回复,它返回“ XXX-XXX”或“ XX-XXXX”

const formatUnitCode = (value,format) => {}

所以基本上,我想看成formatUnitCode("123456","XX-XXX") --> "12-3456"

我不想使用,因为将来可能会以XX-XX-XX的形式出现

有人可以帮助我创建此功能吗?

我尝试使用正则表达式,但是我认为不可能传递变量而不是{2}和{4}

const formatCode = (val) => val.replace(/(\d{2})(\d{4})/g,"$1-$2");

解决方法

您不能在RegExp文字中使用变量,但是可以在使用RegExp()构造函数将模式构建为字符串时使用。

const formatStr = (val,format) => {
  let ptn = format.split('-').map(part => '(.{'+part.length+'})').join('');
      match = val.match(new RegExp(ptn));
  match && console.log(match.slice(1).join('-'));
};

console.log() ptn var看看那里发生了什么很有启发。我们正在使用您任意的基于X的格式来派生新的动态RegExp,它将在多匹配RegExp中使用以捕获零件。

formatStr('123456','xxx-xxx'); //"123-456"
formatStr('123456','xx-xxxx'); //"12-3456"
,

您可以使用简单的for循环制作动态字符串格式的方法。

$('.' + class_name).off("click").click(....)

,

这是您想做的吗?

const func = (val,first_digit) => {
    let regex = new RegExp("(\\d{" + first_digit + "})(\\d{" + (6-first_digit) + "})","g");
    return val.replace(regex,"$1-$2");
};
,

这对于任何掩码都适用,无论使用什么字母(您都可以通过更改匹配器正则表达式来控制该行为)。就个人而言,我认为这不仅仅是尝试将给定的蒙版与正则表达式匹配,而是更具弹性的方法。

const replaceWithFiller = (filler,str,matcher = /[a-zA-z]/g) => {
  const arr = filler.split('');
  return  str.replace(matcher,() => arr.shift());
};


console.log(replaceWithFiller('123456','XXX-XXX')); //"123-456"
console.log(replaceWithFiller('123456','XX-XX-XX')); // "12-34-56"
console.log(replaceWithFiller('123456','XX-XXXX')); //"12-3456"
console.log(replaceWithFiller('123456','aa-aaaa')); // also "12-3456"

,

您可以使用模板文字将参数传递给正则表达式:

const formatCode = (val,format) => {
  const lengthFirstBlock = format.indexOf('-');
  const lehgthSecondBlock = format.length - format.indexOf('-');
  const regex = new RegExp(`(\\d{${lengthFirstBlock}})(\\d{${lehgthSecondBlock}})`,'g');
  return val.replace(regex,"$1-$2");
} 

console.log(formatCode("123456","XX-XXX"))
console.log(formatCode("123456","XXX-XX"))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...