我有這樣的正則運算式函式:
const format = (value) => {
if (typeof value === 'string') {
return value.replace(/(\d{3})(\d )/g, '$1-$2');
}
}
當我在沒有輸入 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))
}
uj5u.com熱心網友回復:
更換事先連字符的所有出現"-"與""(空字串)
const format = (val = "") => val.replace(/-/g, "").replace(/(\d{3})(\d )/g, '$1-$2');
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, '$1-$2'); // 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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409281.html
標籤:
