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
You should enclose the alphabet and the digits in separate capture groups so you can reference them in the replacement string:
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.