I want the newValue to keep the maskValue format, with spaces.
I have for example these two strings, the expected outcome would be this:
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
This is my code:
const formattedValue = (maskValue.split('').filter(
val => val === ' ' || rawValue.split('').includes(val)
))
.join('');
Thanks for the help in advance
4 Answers 4
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)
answered Jun 22, 2022 at 7:22
Mina
17.8k3 gold badges24 silver badges39 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use this approach:
const formattedValue = rawValue.replace(/^(\d{1})(\d{4})(\d{4}).*/, '1ドル 2ドル 3ドル');
2 Comments
karterkortland
Thanks, for the input. but the maskValue is dynamic, so it can be different all the time
Navab Rahimi
No problem, In that case maybe you should use a library.
I would determine the length of the final formattedValue first:
const blankSpaceCount = maskValue.substr(0, rawValue.length).split('').filter(x => x === ' ').length;
const formattedValueLength = rawValue.length + blankSpaceCount;
At the end you can just use substr to reduce the size of the final string:
formattedValue.substr(0, formattedValueLength)
This works dynamically with whatever input is coming.
Comments
Here is how you can format a string using a mask, without having tailing zeros for remaining chars:
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)
answered Jun 22, 2022 at 7:39
Marat
6291 gold badge7 silver badges10 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js