I want to concatenate two strings to make a regular expression so I can have different prefix but same pattern at the back of the string.
If notice, must use doubleĀ back slashes if the regular expression uses back slash. Example instead of \d must use \\d.
Code
1 2 3 4 5 6 7 8 9 10 11 |
const prefix: string = '604'; const pattern: string = ' - \\d{3} \\d{4}'; const regexStr = prefix + pattern; console.log('regex string: ', regexStr); const text = 'Telephone: 604 - 123 4567'; const regex = new RegExp(regexStr, 'gi'); console.log('output: ', regex.exec(text)); |
Output

Demo
You can test the Regex Concatenate Strings here.