最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace chars and keep string length? - Stack Overflow

programmeradmin4浏览0评论

Is possible in js transform a String in this format

123456789

In something like this

*****6789

I want to use just one statment, something like this but keeping the last four characters.

var a = "12312312312123".replace(/[0-9]/g, "*")
console.log(a)

Is possible in js transform a String in this format

123456789

In something like this

*****6789

I want to use just one statment, something like this but keeping the last four characters.

var a = "12312312312123".replace(/[0-9]/g, "*")
console.log(a)

Share Improve this question asked Mar 14, 2019 at 0:02 Rafael UmbelinoRafael Umbelino 8108 silver badges15 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

you could make use of .(?=.{4}) with g flag:

var a = "12312312312123".replace(/.(?=.{4})/g, '*')
console.log(a)

Split the input into substrings, perform the replacement on the first part, and then append the second part.

var input = "123-456-7890";
var prefix = input.substr(0, input.length - 4);
var suffix = input.substr(-4);
var masked = prefix.replace(/\d/g, '*');
var a = masked + suffix;
console.log(a)

Use padStart

const str = '123456789';
console.log(str.slice(-4).padStart(str.length, '*'));

Or

const str = '123456789';
console.log(str.substr(-4).padStart(str.length, '*'));

A slightly different approach... by creating two capture groups and replacing the first with * repeated.

const a = '123456789'.replace(/(^\d+)(\d{4}$)/, (m,g1,g2) => '*'.repeat(g1.length) + g2);
console.log(a);

You can use either the function slice or function substr and the function padStart to fill * from left-to-right.

let str = "1234567893232323232";
console.log(str.slice(5, str.length).padStart(str.length, '*'));

发布评论

评论列表(0)

  1. 暂无评论