-1

I'm trying to match some paragraphs in Google Docs but the pattern that I wanted to use for it doesn't match the string when run inside a Google Script. However, it works properly on regex101 so I guess I'm missing something. Do you know what?

This is a sample of what I have:

function test() {
  var str = "brown fox → jumps over the lazy dog";
  var definitionRe = new RegExp('([\w\s]+)\s+[\u2192]\s+(.+)', 'g');
  var definitionMatch = definitionRe.exec(str); // null

  var dummy = "asdf"; // makes the debugger happy to break here
}
t3chb0t
  • 16,340
  • 13
  • 78
  • 118

1 Answers1

0

When using a string regex such as new RegExp(...), you need to escape your \'s, so then the following:

var definitionRe = new RegExp('([\w\s]+)\s+[\u2192]\s+(.+)', 'g');

Will become an escaped version like this:

var definitionRe = new RegExp('([\\w\\s]+)\\s+[\\u2192]\\s+(.+)', 'g');

Otherwise you can do a non string version, but you then can no longer concatenate values to the string (If that is something you would like):

var definitionRe = /([\w\s]+)\s+[\u2192]\s+(.+)/g;
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338