【问题标题】:Replace all characters in specific group to asterisks将特定组中的所有字符替换为星号
【发布时间】:2016-12-07 23:56:29
【问题描述】:

我发现this SO 帖子很接近,但我想稍微扩展一下这个问题。

我需要将每个字符(在一组正则表达式中)替换为星号。例如

Hello, my password is: SecurePassWord => Hello, my password is: **************

我有一个正则表达式可以将其分组,但我不知道如何应用此示例(来自链接):str.replace(/./g, '*');

到这样的东西:str.replace(/(Hello, my password is\: )(\w+)/g, '$1...'); 其中... 是将字符从 $2 转换为星号的魔法。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以将replacement functionString.prototype.replace 一起使用,这将获得匹配的文本和组。

    var input = 'Hello, my password is: SecurePassWord';
    var regex = /(Hello, my password is: )(\w+)/;
    var output = input.replace(regex, function(match, $1, $2) {
      // $1: Hello, my password is: 
      // $2: SecurePassWord
      // Replace every character in the password with asterisks
      return $1 + $2.replace(/./g, '*');
    });
    console.log(output);

    【讨论】:

      【解决方案2】:

      如果你不是特别需要正则表达式。

      与:

      var password = "something";
      

      你可以这样做:

      var mystring = "My passsword is " + Array(password.length).join("*");
      

      或者:

      var mystring = "My passsword is " + password;
      mystring = mystring.replace(password, Array(password.length).join("*"));
      

      【讨论】:

        猜你喜欢
        • 2018-09-10
        • 1970-01-01
        • 2013-06-27
        • 2011-11-11
        • 2020-07-02
        • 1970-01-01
        • 2014-04-07
        • 2018-12-07
        相关资源
        最近更新 更多