Home > Blockchain >  Replace text using regular expressions js vanilla
Replace text using regular expressions js vanilla

Time:09-30

I am trying to replace the text of an input. If I enter this value (11111111), the output format should be (1,111,111-1). I have no idea how to do this using js vanilla. I am trying to use regex and replace but I'm very confused.

let regExp = /^[1-9].\d{3}.\d{3}-\d{1}$/g;  
let newInput = input.replace(regExp, '$1,');
console.log( newInput);

CodePudding user response:

The regex is for the match, which must match the input string. Use the replacement pattern to reformat the output:

let input = '11111111'
let regExp = /^(\d)(\d{3})(\d{3})(\d)$/g;  
let newInput = input.replace(regExp, '$1,$2,$3-$4');
console.log( newInput);

  • Related