简体   繁体   English

用 # 替换所有字符,最后 4 个字符除外

[英]Replace all chars with #, except for last 4

function maskify(cc) {
    var dd = cc.toString();
    var hash = dd.replace((/./g), '#');
    for (var i = (hash.length - 4); i < hash.length; i++) {
        hash[i] = dd[i];
    }
    return hash;
}

I am trying to replace all chars with # except for last 4. Why isn't it working?我正在尝试用#替换所有字符,最后 4 个字符除外。为什么它不起作用?

You could do it like this:你可以这样做:

dd.replace(/.(?=.{4,}$)/g, '#');

 var dd = 'Hello dude'; var replaced = dd.replace(/.(?=.{4,}$)/g, '#'); document.write(replaced);

If you find the solution, try this trick如果您找到解决方案,请尝试此技巧

function maskify(cc) {
  return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}

To replace a character in a string at a given index, hash[i] = dd[i] doesn't work.要在给定索引处替换字符串中的字符, hash[i] = dd[i]不起作用。 Strings are immutable in Javascript.字符串在 Javascript 中是不可变的。 See How do I replace a character at a particular index in JavaScript?请参阅如何替换 JavaScript 中特定索引处的字符? for some advice on that.一些建议。

尝试这个:

return cc.replace(/.(?=.{4})/g, "#");
function maskify(cc) {
  let arr = cc.split('');
  for (let i = 0; i < arr.length - 4; i++){
    arr[i] = '#';
  }
  return arr.join('');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM