Creating a regular expression to replace every matching character in a string with the same character

In my application, I have an alphanumeric string passed to my function. This line is usually 17 characters long, but not always. I am trying to write a regex that matches all but the last 4 characters in the string and replaces them with X (to mask it).

for example

Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H

      

Regex I written to perform inline replacements looks like this

[a-zA-Z0-9].{12}

      

Code:

const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');

      

The problem I'm running into is that it replaces everything but the last 4 characters in the string with only one single X. It doesn't know what to do for each matched character. Any ideas?

+3


source to share


4 answers


Look ahead ( ?=

)
to make sure there are at least four following characters.

const regex = /.(?=....)/g;
//             ^             MATCH ANYTHING
//              ^^^^^^^^     THAT IS FOLLOWED BY FOUR CHARS

function fix(str) { return str.replace(regex, 'X'); }

const test = "HGHG8686HGHG8686H";

// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();
      

<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>
      

Run codeHide result


Irregular solution:



const test = "HGHG8686HGHG8686H";

function fix(str) {
  return 'X'.repeat(str.length - 4) + str.slice(-4);
}
  
console.log(fix(test));
      

Run codeHide result


You won't find it String#repeat

in IE.

+1


source


you can use a function inside replace to do it, something like this:



var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
    return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);
      

Run codeHide result


+1


source


Simple version: (easier to read)

const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1

      

Now using: [a-zA-Z0-9]

const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1

      

Note: the reason why I match two START PLUS characters is the offset of the first match. (The final 4 characters are added at the end.)

+1


source


You can use the following method:

      var str = "HGHG8686HGHG8686H"

      var replaced=''

      var match = str.match(/.+/)
    
      for(i=0;i<match[0].length-4;i++){
        
          str = match[0][i]
        
          replaced += "X"
        
      }

      replaced += match[0].substr(match[0].length-4)

      console.log(replaced);
      

Run codeHide result


0


source







All Articles