10

I need to put a received string in this format:

"## ## ## ###" in typescript/javascript

Eg:

"12 34 56 789"

I know there's string-mask and some way via JQuery, is there a simplier way to do it?

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Pedro Pam
  • 375
  • 1
  • 4
  • 14

3 Answers3

42

You could replace each pattern part with the wanted data.

function format(value, pattern) {
    let i = 0;
    const v = value.toString();
    return pattern.replace(/#/g, _ => v[i++]);
}

console.log(format(123456789, '## ## ## ###'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

I needed one that masks any character with a "*", from the beginning or end of the string, so I wrote the following:

"use strict";

module.exports = {
  /**
   * @param {string} str
   * @param {string} maskChar
   * @param {number} unmaskedLength
   * @param {boolean} [maskFromStart]
   * @returns {string}
   */
  mask(str, maskChar, unmaskedLength, maskFromStart = true) {
    const maskStart = maskFromStart ? 0 : Math.max(0, unmaskedLength);
    const maskEnd = maskFromStart ? Math.max(0, str.length - unmaskedLength) : str.length;
    return str
      .split("")
      .map((char, index) => {
        if (index >= maskStart && index < maskEnd) {
          return maskChar;
        }
        else {
          return char;
        }
      })
      .join("");
  },
};
Paul Milham
  • 526
  • 5
  • 13
0

The one which worked for me with the format xxx-xxx-xxxx with keyup event

stringOnKeyUp.replace(/^(\d{3})$/g, '$1-').replace(/^(\d{3}-\d{3})$/g, '$1-');
CandleCoder
  • 1,387
  • 4
  • 21
  • 45