如何为(-)创建正则表达式,在 formik setfieldvalue 中的 3 位数字后不重复
how to create regex for (-) not repeat after 3 digit inside formik setfieldvalue
我有这样的正则表达式函数:
const format = (value) => {
if (typeof value === 'string') {
return value.replace(/(\d{3})(\d+)/g, '-');
}
}
当我在没有输入 formik setfieldvalue 的情况下进行控制台时,它会生成正确的正则表达式,如 111-1111111:
const custom = (value) => {
console.log('valuemain',format(value)); //this valuemain: 111-1111111
formikRef.current.setFieldValue('customnumb',value)
}
但是当我将正则表达式输入 formik setfieldvalue 时,它变成了 111-111-111:
const custom = (value) => {
console.log('valuemain',format(value)); //this valuemain: 111-111-111
formikRef.current.setFieldValue('customnumb',format(value))
}
预先将所有出现的连字符 "-"
替换为 ""
(空字符串)
const format = (val = "") => val.replace(/-/g, "").replace(/(\d{3})(\d+)/g, '-');
console.log(format("1111111111")); // "111-1111111"
console.log(format("111-1111111")); // "111-1111111"
console.log(format("111-11-1-1-1-11")); // "111-1111111"
显然 您只对整数感兴趣;为了在政治上更正确,而不是只替换连字符 "-"
你可以替换(使用 RegExp \D
Not a Digit) - 一切都是 不是数字:
const format = (val = "") => {
// @TODO: do val checks if needed here.
return val
.replace(/\D/g, "") // Remove everything that is not a digit
.replace(/(\d{3})(\d+)/g, '-'); // Format as desired
};
console.log(format("1111111111")); // "111-1111111"
console.log(format("111-1111111")); // "111-1111111"
console.log(format("111-11-1-1-1-11")); // "111-1111111"
我有这样的正则表达式函数:
const format = (value) => {
if (typeof value === 'string') {
return value.replace(/(\d{3})(\d+)/g, '-');
}
}
当我在没有输入 formik setfieldvalue 的情况下进行控制台时,它会生成正确的正则表达式,如 111-1111111:
const custom = (value) => {
console.log('valuemain',format(value)); //this valuemain: 111-1111111
formikRef.current.setFieldValue('customnumb',value)
}
但是当我将正则表达式输入 formik setfieldvalue 时,它变成了 111-111-111:
const custom = (value) => {
console.log('valuemain',format(value)); //this valuemain: 111-111-111
formikRef.current.setFieldValue('customnumb',format(value))
}
预先将所有出现的连字符 "-"
替换为 ""
(空字符串)
const format = (val = "") => val.replace(/-/g, "").replace(/(\d{3})(\d+)/g, '-');
console.log(format("1111111111")); // "111-1111111"
console.log(format("111-1111111")); // "111-1111111"
console.log(format("111-11-1-1-1-11")); // "111-1111111"
显然 您只对整数感兴趣;为了在政治上更正确,而不是只替换连字符 "-"
你可以替换(使用 RegExp \D
Not a Digit) - 一切都是 不是数字:
const format = (val = "") => {
// @TODO: do val checks if needed here.
return val
.replace(/\D/g, "") // Remove everything that is not a digit
.replace(/(\d{3})(\d+)/g, '-'); // Format as desired
};
console.log(format("1111111111")); // "111-1111111"
console.log(format("111-1111111")); // "111-1111111"
console.log(format("111-11-1-1-1-11")); // "111-1111111"