Masking a string

Viewed 23829

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?

3 Answers

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("");
  },
};

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

Related