0

I created the following pattern: ((\s|[0-9])[0-9]{1}:[0-9]{2}\sPM:)

This regular expression will work to find the following pattern: Giving the following text "Christina Perry 8:30 PM:" it should match with 8:30 PM: or 18:30 PM:.

It's working properly here https://regex101.com/r/DouyiU/2 however, it's always returning false in my JavaScript code:

var patt = new RegExp("((\s|[0-9])[0-9]{1}:[0-9]{2}\sPM:)");
return (patt.test("Christina Perry 8:30 PM:"));

The desired result is to return true, or: Yes, there is this pattern on the giving sentence;

What am I doing wrong?

Dan
  • 1,518
  • 5
  • 20
  • 48
  • 1
    Each backslash when you use a string as RegExp constructor parameter must be escaped with an other backslash. `{1}` doesn't make sense, never, remove it. – Casimir et Hippolyte May 10 '17 at 21:46
  • 1
    I think you can use a regexp literal instead `/(\s|[0-9])[0-9]{1}:[0-9]{2}\sPM:/` which removes the need for escaping. Works in Chrome for me. – Mauro Bringolf May 10 '17 at 21:46
  • @CasimiretHippolyte you're right, it worked to me. – Dan May 10 '17 at 21:49
  • @MauroBringolf I'm not familiar with RegExp. I don't know what do you mean about needs for escaping – Dan May 10 '17 at 21:50
  • 1
    Good news, also `(\\s|[0-9])` can be replaced with `[0-9\\s]`. Consider also Mauro way (see the mdn page for RegExp: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). – Casimir et Hippolyte May 10 '17 at 21:50

1 Answers1

3

Try this (use regex literals):

var patt = /((\s|[0-9])[0-9]{1}:[0-9]{2}\sPM:)/;
return (patt.test("Christina Perry 8:30 PM:"));

I recommend that you always use regex literals except when regex object (i.e. new RegExp()) is really required. The reason is that regex literals are easier to use and more readable in most cases. For instance, in your case you don't need to worry about escaping the backslash.

An example of when a regex object is required: when the regex pattern is constructed from variables or constructed in several steps.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • 1
    Add that the literal form `/.../` will be "hoisted", or "compiled" at parse-time by the browser's js engine. The "constructor" form `new RegExp('...')` will be compiled and a new instance created on every time the function is run, at run-time. – 000 May 10 '17 at 21:55