我在react-native上的应用程序上有一个数字类型输入字段。
此字段只能接受逗号。
所以我使用了:keyboardType="数字"
但在这种情况下,仍然可以使用点、空格和线(-)等字符。除了输入错误数字数据时的任何错误。
正确的格式应该是这样的:nnn, ddd
你能帮我一把吗?
let a = [
"0",//0
"0,5",//0,5
"0,,5",//0,5
"0.5",//0,5
"0..5",//0,5
".0.5",//0,5
",0,5",//0,5
"0.-5,",//0,5
"0,-5.",//0,5
"0,5-..",//0,5
"0,,,- 5,,",//0,5
"0...5- ",//0,5,
"0,5,"//0.5,
];
a.map(el=> {
const e = el
.replaceAll('.', ',')
.replace(/[^0-9,]/g, '')
console.log(e)
});
编辑:
let a = [
"0",//0
"0,5",//0,5
"0,,5",//0,5
"0.5",//0,5
"0..5",//0,5
".0.5",//0,5
",0,5",//0,5
"0.-5,",//0,5
"0,-5.",//0,5
"0,5-..",//0,5
"0,,,- 5,,",//0,5
"0...5- ",//0,5,
"00,5",//0,5
"00,05",//0,05
"05,512",//5,51
"00,5123",//0,51
",05",//0,05
"00,,5",//0,5
"21,"//21
];
这里有一点混合字符串操作与正则表达式混合。在编辑条件下变成了一个怪物,但这里是:
a.map(el => {
const e = el
/* normalize decimals */
.replaceAll('.', ',')
/* break into array */
.split(",")
/* add a starting zero */
.map((e,i) => i === 0 ? "0"+e : e)
/* get rid of empties (extra commas) */
.filter(e => e)
/* only work with the last 2 */
.splice(-2)
/* remove non-numbers */
.map(e => e.replace(/[^0-9.]/g, ''))
/* trim index 0 & 1 */
.map((e, i) => i === 0 ? (+e || "0") : e.substr(0, 2))
/* reassemble */
.join(",");
console.log(el, '=>', e)
});
let a = [
"0", //0
"0,5", //0,5
"0,,5", //0,5
"0.5", //0,5
"0..5", //0,5
".0.5", //0,5
",0,5", //0,5
"0.-5,", //0,5
"0,-5.", //0,5
"0,5-..", //0,5
"0,,,- 5,,", //0,5
"0...5- ", //0,5,
"00,5", //0,5
"00,05", //0,05
"05,512", //5,51
"00,5123", //0,51
",05", //0,05
"00,,5", //0,5
"21," //21
];
a.map(el => {
const e = el.replaceAll('.', ',').split(",").map((e,i) => i === 0 ? "0"+e : e).filter(e => e).splice(-2).map(e => e.replace(/[^0-9.]/g, '')).map((e, i) => i === 0 ? (+e || "0") : e.substr(0, 2)).join(",");
console.log(el, '=>', e)
});
您可以使用
let a = [
"0",//0
"0,5",//0,5
"0,,5",//0,5
"0.5",//0,5
"0..5",//0,5
".0.5",//0,5
",0,5",//0,5
"0.-5,",//0,5
"0,-5.",//0,5
"0,5-..",//0,5
"0,,,- 5,,",//0,5
"0...5- ",//0,5,
"00,5",//0,5
"00,05",//0,05
"05,512",//5,51
"00,5123",//0,51
",05",//0,05
"00,,5",//0,5
"21,"//21
];
a.map(el=> {
const e = el
.replace(/^[.,]+(?=[^.,]*$)/, '0,') // Add 0 before the first . or , if they are single
.replace(/^\D+|\D+$|[^0-9,.]/g, '') // remove all non-digits on both sides and non-digits except . and , in the middle
.replace(/[,.]+/g, ',') // all commas/dots to commas
.replace(/^0+(?=\d)|,(?=[^,]*,)|(,\d{2})\d+$/g, '$1') // remove leading zeros, all commas but last, and all fractional digits after 2nd
console.log(el,'=>',e);
});
自我解释
let a = [
"0",//0
"0,5",//0,5
"0,,5",//0,5
"0.5",//0,5
"0..5",//0,5
".0.5",//0,5
",0,5",//0,5
"0.-5,",//0,5
"0,-5.",//0,5
"0,5-..",//0,5
"0,,,- 5,,",//0,5
"0...5- ",//0,5,
"0,5,"//0.5
];
a.map(el=> {
const e = el
.replace(/\D+/g, ',') // replace non digit with comma
.replace(/^,|,$/g, '') // trim the comma
console.log(e)
});