'RegExp constructor adding unexpected comma to pattern

trigoOperators is an array containing some trigonometric operations.

The goal is to create a regular expression that parses a string equation into an array.

The problem is that the resulting regular expression is adding an unexpected comma to the pattern as shown in the example below

const trigoOperators = ['abs', 'sqrt']

const rexExp = new RegExp('\\W|(-?\\d+)' + `${(trigoOperators.map(o => `|(${o})`))}`, 'g')

console.log(rexExp)

The expected result is /\W|(-?\d+)|(abs)|(sqrt)/g while the current result is /\W|(-?\d+)|(abs),|(sqrt)/g (notice the added comma)



Solution 1:[1]

The .map() method returns an array. When the template expansion expands that, it'll .join() it into a string. That's where the comma comes from. You can override the default .join() string:

const trigoOperators = ['abs', 'sqrt']

const rexExp = new RegExp('\\W|(-?\\d+)' + `${(trigoOperators.map(o => `|(${o})`)).join('')}`, 'g')

console.log(rexExp)

Solution 2:[2]

The comma appears because the array was coerced to a string.

You can use

const trigoOperators = ['abs', 'sqrt']
const rexExp = new RegExp(String.raw`\W|(-?\d+)${trigoOperators.map(o=>`|(${o})`).join('')}`, 'g')
console.log(rexExp) // => /\W|(-?\d+)|(abs)|(sqrt)/g

Details:

  • String.raw... - definition of a raw string literal where a backslash is treated as a literal
  • ${trigoOperators.map(o=>`|(${o})`).join('')} - takes each item inside trigoOperators array, wraps them with |( and ) chars, and then concatenates the items (using .join('')).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pointy
Solution 2