'Masking a string

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?



Solution 1:[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("");
  },
};

Solution 2:[2]

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-');

Solution 3:[3]

I fixed the problem by Uninstalling Node.js and removing all modules from my computer and doing a fresh re-install of everything and now it works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Milham
Solution 2 CandleCoder
Solution 3 user2957160