Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
Pedro Pam Avatar asked Jul 11 '17 10:07

Pedro Pam


People also ask

What is string mask?

The mask may be alphabetic, numeric or contain blank characters or any of the special characters valid within a string name. For an inclusive mask the string is accepted for further processing; for an exclusive mask the string is rejected.

What is masking in Java?

Data masking is a method of creating a structurally similar version of an organization´s data that can be used for purposes such as software testing and user training. The purpose of data masking is to protect the actual data while having a functional substitute when the real data is not required.

What is the function of masking?

Protective masks are pieces of kit or equipment worn on the head and face to afford protection to the wearer, and today usually have these functions: Providing a supply of air or filtering the outside air (respirators and dust masks).


2 Answers

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, '## ## ## ###'));
like image 167
Nina Scholz Avatar answered Nov 15 '22 21:11

Nina Scholz


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("");
  },
};
like image 29
Paul Milham Avatar answered Nov 15 '22 21:11

Paul Milham