Search code examples
javascriptmasking

Masking of variable length string in JavaScript


I want to mask a string in ReactJS, as in replacing the first N characters with the * symbol. But I want N to be variable.

Example:

const item = '1234567890'
const masked = masked(item, 6);
console.log(masked); // '******7890'

Solution

  • If I get you correctly you could just try this:

    const item = '1234588567890';
    
    // How many letters you want to leave readable at the end
    const cutoff = 4;
    const formattedItem = '*'.repeat(item.length - cutoff) + item.slice(-cutoff);
    
    console.log(formattedItem)