0

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

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this approach:

const formattedValue = rawValue.replace(/^(\d{1})(\d{4})(\d{4}).*/, '$1 $2 $3');

2 Comments

Thanks, for the input. but the maskValue is dynamic, so it can be different all the time
No problem, In that case maybe you should use a library.
0

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

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.