Home > Enterprise >  format string to another string format
format string to another string format

Time:06-22

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

CodePudding user response:

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)

CodePudding user response:

You can use this approach:

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

CodePudding user response:

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.

CodePudding user response:

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)
  • Related