简体   繁体   English

将字符串格式化为另一种字符串格式

[英]format string to another string format

I want the newValue to keep the maskValue format, with spaces.我希望 newValue 保留带有空格的 maskValue 格式。

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我在这里先向您的帮助表示感谢

 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)

You can use this approach:您可以使用这种方法:

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

I would determine the length of the final formattedValue first:我将首先确定最终 formattedValue 的长度:

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:最后你可以只使用substr来减少最终字符串的大小:

formattedValue.substr(0, formattedValueLength)

This works dynamically with whatever input is coming.这可以动态地处理任何输入。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM