-1

I have the following as an excerpt from string - data:

"From c7a06712edc4d2f633f71bef92ba804c3183b380 Mon Sep 17 00:00:00 2001\r\nFrom: George Edwards r\nDate: Mon, 8 Aug 2016 09:52:43 +0100\r\nSubject: [PATCH] init\r\n\r\n---\r\n package.json | 36 ++++++++++++++++++++++++++++++++++++\r\n 1 file changed, 36 insertions(+)\r\n create mode 100644 package.json\r\n\r\ndiff --git a/package.json

Then I run the following code, but from the debugger, I can see sha is equalling null.

var patt = new RegExp('/From (.*?)\s/g');
var sha = patt.exec(data);

I tried this on regexr and it showed this as a match. Why isn't it working in Javascript?

George Edwards
  • 8,979
  • 20
  • 78
  • 161
  • 1
    When using `RegExp` constructor to create RegEx, the delimiters are not required. `new RegExp('/From (.*?)\s/g');` ==> `new RegExp('From (.*?)\s', 'g');` **OR** simply use regex literal syntax `/From (.*?)\s/g` – Tushar Aug 18 '16 at 13:28
  • Read the [MDN on RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), that is not how you use it – epascarello Aug 18 '16 at 13:28

1 Answers1

1

One of the way you can make it as :

var data = "From c7a06712edc4d2f633f71bef92ba804c3183b380 Mon Sep 17 00:00:00 2001\r\nFrom: George Edwards r\nDate: Mon, 8 Aug 2016 09:52:43 +0100\r\nSubject: [PATCH] init\r\n\r\n---\r\n package.json | 36 ++++++++++++++++++++++++++++++++++++\r\n 1 file changed, 36 insertions(+)\r\n create mode 100644 package.json\r\n\r\ndiff --git a/package.json";

var patt = /From (.*?)\s/g;
//or var patt = new RegExp(/From (.*?)\s/,'g');
var sha = patt.exec(data);

console.log(sha);
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44