Cédric
Cédric

Reputation: 180

Character replacement mask over a string in javascript

I need to apply a replacement mask over a string in javascript. The mask is a user input with the following syntax:

I have come up with the following code that appears to be working but I am wondering if there is a better way to achieve this with a single regular expression or any other way (no library please).

Thank you

var reference = '123-45678-000';
var mask ='###W#####-9##';
var newReference = mask;

while ((match = /#{1}/.exec(newReference)) != null) {
   newReference =  newReference.substring(0, match.index) + reference.substring(match.index,match.index+1) + newReference.substring(match.index + 1);
}
console.log("old : " +  reference);      //prints 123-45678-000
console.log("mask: " +  mask);           //prints ###W######9##
console.log("new : " +  newReference);   //prints 123W45678-900

Upvotes: 0

Views: 6428

Answers (2)

LinuxDisciple
LinuxDisciple

Reputation: 2379

var reference = '123-45678-000';
var mask ='###W#####-9##';
var newReference = "";

for (var n=0;n<reference.length;n++){
    newReference+=( mask.charAt(n) == '#' )?reference.charAt(n):mask.charAt(n);
}

Upvotes: 1

DrC
DrC

Reputation: 7698

Try the following:

newReference = mask.replace(/#/g,function(m,o) {return reference[o];});

Upvotes: 1

Related Questions