Reputation: 57
I am trying to convert regular expression format into a mask-input string to guide the user to enter the correct input on the UI. Numbers would be represented by "#" and letter by "A".
Basically,
"^\d{3}$" --> "###"
"^(GB)\d{3}$" --> "GB###"
"^\d{2}\.\d{3}\/\d{4}-\d{2}$" --> "##.###/####-##"
"^\d{2}[ ]\d{3}[ ]\d{3}$" --> "## ### ###"
function convertToMaskInput(regex){
}
convertToMaskInput("^\d{4}$");
//Output: "####"
I am beginner to Javascript and I am having hard time to do this dynamically. Any help or guidance is appreciated.
Thanks in advance!
Upvotes: 3
Views: 3908
Reputation: 16779
If your goal is to handle every possible variant of regular expression, you should probably use an existing plugin rather than rolling your own solution.
However, for the sake of completeness, here is an implementation that can deal with the subset of cases you gave as examples:
function convertToMaskInput(regex) {
return new RegExp(regex).source
.replace(/^\^|\$$/g, '')
.replace(/\\d/g, '#')
.replace(/\(([^)]*)\)|\[([^^])\]|\\([\\/.(){}[\]])/g, '$1$2$3')
.replace(/([\w#.-])\{(\d+)\}/gi, function (_, c, n) {
return Array(+n + 1).join(c)
})
}
convertToMaskInput("^\d{4}$")
console.log([
/^\d{3}$/, //=> "###"
/^(GB)\d{3}$/, //=> "GB###"
/^\d{2}\.\d{3}\/\d{4}-\d{2}$/, //=> "##.###/####-##"
/^\d{2}[ ]\d{3}[ ]\d{3}$/ //=> "## ### ###"
].map(convertToMaskInput))
Upvotes: 2