Eko Rudiyanto jay Eko Rudiyanto jay - 16 days ago 5
Javascript Question

text length more than 3 string than replace rest with another string

How to replace the rest of a string more than 3 character swith another character?

ex :

var str = "John Doe";


I want output with

Johxxxxx

Answer

Use String#replace method with a callback function

var str = "John Doe";

console.log(
  str.replace(/^(.{3})(.+)$/, function(_, m1, m2) {
    return m1 + // first 3 characters
      new Array(m2.length + 1).join('x'); // generate string with  length of remaining character 
  })
)


Or use String#slice method.

var str = "John Doe";

console.log(
    str.slice(0, 3) + // get first three character
    new Array(str.length > 2 ? str.length - 2 : 0).join('x') // generate string with remaining length
)

Comments