Javascript [SOLVED]: How to replace the characters leaving last 4 letters

Javascript [SOLVED]: How to replace the characters leaving last 4 letters

Home Forums Scripting Javascript Tutorials Javascript [SOLVED]: How to replace the characters leaving last 4 letters

Tagged: ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245681

    Cloudy Point
    Keymaster

    QuestionQuestion

    I am trying to replace all characters leaving last four characters. I am trying the following to do that:

    var string = params.toString();
        string = string.replace(/^.{12}/g,'************');
    
        return string;
    

    at present my string length is 16, But my question is, when my string length changes from 16 to 12 or some other length, I will get the issue because of using the static 12 and * hash letters.

    so, how to get alway replace the * only on leaving last 4 characters?

    #245682

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    The following will work:

    var input = "123456789";
    var output = input.replace(/.(?=.{4})/g, '*');
    console.log(output);

    It just does a global replace on all characters which are followed by at least four other characters. Since the last four characters won’t have four more that come after them, they won’t be replaced. Each matching character is replaced by a single asterisk character.

    Source: https://stackoverflow.com/questions/48016977/how-to-replace-the-characters-leaving-last-4-letters
    Author: Steven Doggart
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.