typescript 屏蔽字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45031441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:42:31  来源:igfitidea点击:

Masking a string

javascriptstringtypescriptmasking

提问by Pedro Pam

I need to put a received string in this format="## ## ## ###" in typescript/javascript. ( like "12 34 56 789).

我需要在 typescript/javascript 中以这种格式放置一个接收到的字符串 =“## ## ## ###”。(如“12 34 56 789)。

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

我知道有“字符串掩码”和通过 JQuery 的某种方式,有没有更简单的方法来做到这一点?

回答by Nina Scholz

You could replace each pattern part with the wanted data.

您可以用所需的数据替换每个模式部分。

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

console.log(format(123456789, '## ## ## ###'));

回答by Paul Milham

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