George Edwards George Edwards - 3 months ago 9
Javascript Question

RegExp returning null despite containing a match

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?

Answer

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);

Comments