-4

After reading this Question I am trying to use this regex

/(!<[^>]+>)+/g

Like this

var regex = /(!<[^>]+>)+/g;
new RegExp('myString', regex)

but I get

Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '/(!<[^>]+>)+/g'

Anybody have idea how to use it right?

2 Answers2

1

new Regexp is used when you have a regular expression in a string and you want to convert it to a regular expression object.

It is awful and you should almost never use it. (The exception is when you are dynamically generating a regex).

You don't need to use it: You created the object using a regular expression literal on the previous line.


To apply the regular expression to a string, use the match method:

var regex = /(!<[^>]+>)+/g;
console.log("myString".match(regex));
console.log("Trivial !<tag> example".match(regex));
console.log("!<tag attribute='>>>'> example".match(regex));

(But applying regex to HTML is usually a terrible idea).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

RegExp is used to create regular expression from string

The second attribute should be flags like i , g, m but you're giving a regular expression itself.

The syntax of RegExp is RegExp(regexString,flags)

but you are using

var regex = /(!<[^>]+>)+/g;
new RegExp('myString', regex)
                       ^^^^^^

You can't use the RegExp function to test a string.

if you want to check 'myString' against your regular expression, use regex.test('myString')

if you want to find all matches of the regex in 'myString', use 'myString'.match(regex)

Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • "That's the problem" — That's a symptom. The problem is that `new RegExp` is used to create regular expression objects, not to apply regular expression objects to strings. – Quentin Aug 23 '17 at 11:06
  • agree. in first rev, I pointed out a big mistake in the question. Edited now – Sagar V Aug 23 '17 at 11:12