我希望 newValue 保持 maskValue 格式,帶有空格。
例如,我有這兩個字串,預期的結果是:
maskValue: "0 0000 0000 0000" <= initial maskValue
rawValue: "251551220"
As i type the maskValue changes to: "2 5155 1220 0000"
newValue = "2 5155 1220" <= expected result
2 5155 1220 0000 <= current result, it adds the rest of the zeros
這是我的代碼:
const formattedValue = (maskValue.split('').filter(
val => val === ' ' || rawValue.split('').includes(val)
))
.join('');
我在這里先向您的幫助表示感謝
uj5u.com熱心網友回復:
const maskValue = "0 0000 0000 0000"
const rawValue = "251551220"
const result = []
const pieces = maskValue.split(' ').map(piece => piece.length)
const slice = (str, pieces) => {
let secondPiece = str
pieces.forEach(piece => {
const firstPiece = secondPiece.slice(0, piece)
result.push(firstPiece)
secondPiece = secondPiece.slice(piece);
})
}
slice(rawValue, pieces)
const rawValueWithMask = result.join(' ')
console.log(rawValueWithMask)
uj5u.com熱心網友回復:
您可以使用這種方法:
const formattedValue = rawValue.replace(/^(\d{1})(\d{4})(\d{4}).*/, '$1 $2 $3');
uj5u.com熱心網友回復:
我將首先確定最終 formattedValue 的長度:
const blankSpaceCount = maskValue.substr(0, rawValue.length).split('').filter(x => x === ' ').length;
const formattedValueLength = rawValue.length blankSpaceCount;
最后,您可以使用它substr
來減小最終字串的大小:
formattedValue.substr(0, formattedValueLength)
這可以動態地與任何輸入一起作業。
uj5u.com熱心網友回復:
以下是如何使用掩碼格式化字串,而無需為剩余的字符添加尾零:
const maskValue = '0 0000 0000 0000'
const rawValue = '251551220'
let maskIndex = 0
let formattedValue = ''
rawValue.split('').forEach(char => {
if (maskIndex < maskValue.length && maskValue[maskIndex] === ' ') {
formattedValue = ' '
maskIndex
}
formattedValue = char
maskIndex
})
console.log(formattedValue)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494248.html
標籤:javascript 数组 细绳 筛选 格式
上一篇:如何在javascript中使用正則運算式提取字串值?[復制]
下一篇:陣列,我如何同時顯示標題和描述?