Home > Mobile >  RegExp constructor adding unexpected comma to pattern
RegExp constructor adding unexpected comma to pattern

Time:05-15

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)

CodePudding user response:

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)

CodePudding user response:

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('')).
  • Related