skip to Main Content

How to insert a bracket between the specified alphabet (i.e. A, D, F, R) and the digit using regular expression?

input:

A1
F42
D3
R6

Expected output:

(A)1
(F)42
(D)3
(R)6

What I have tried:

let inputString="f42"
let expPattern=/[ADFR]d{1,3}/ig;
 console.log(inputString.replace(expPattern,"(`$0`)"));

It returns "$0" only.

How can I implement the replacement?

2

Answers


  1. You should enclose the alphabet and the digits in separate capture groups so you can reference them in the replacement string:

    let inputString="F42"
    let expPattern=/([ADFR])(d{1,3})/ig;
    console.log(inputString.replace(expPattern,"($1)$2"));
    Login or Signup to reply.
  2. If you want to use the full match in the replacement, you can make use of a positive lookahead (?=d{1,3}b) asserting 1-3 digits to the right.

    To prevent partial matches, you can use word boundaries b

    In the replacement use the full match denoted as $&

    See a regex demo with all the replacements.

    let inputString="F42"
    let expPattern=/b[ADFR](?=d{1,3}b)/ig;
    console.log(inputString.replace(expPattern,"($&)"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search