Kammryn Dancy Kammryn Dancy - 4 months ago 8
Node.js Question

Difference in javascript regex behaviour from online tools and in actual code

I am using http://regexr.com/3duh0 this regex

(?:\S+\s)?\S*Environment Canada\S?


on this string


Flash Flood Watch in effect until Friday, 2:00 AM EDT. Rainfall
Warning in effect until 8:40 PM MDT. Source: Environment Canada


and while it works all fine and dandy online when i apply that to my code it acts differently and i can't make heads or tails why.

I am using node 0.10.32 (I know, but i have no choice on the version),

var regexFindSource= new RegExp('(?:\S+\s)?\S*Environment Canada\S?');
var summary = 'Flash Flood Watch in effect until Friday, 2:00 AM EDT. Rainfall Warning in effect until 8:40 PM MDT. Source: Environment Canada'
source = summary.match(regexFindSource);
console.log(source);
//The results of this bit of code are
//What i want is 'Source: Environment Canada'
//What i get is 'Environment Canada'


The reason i am basing the regex on Environment Canada is because i want to insert a variable in the place of Environment Canada something like this

var source = wwArray.Source;
var regexFindSource= new RegExp('(?:\S+\s)?\S*' + source + '\S?');

Pat Pat
Answer

Add a '\' before \S* and a ': 'after

var regexFindSource= new RegExp('(?:\S+\s)?\\S*: Environment Canada\S?');
var summary = 'Flash Flood Watch in effect until Friday, 2:00 AM EDT.  Rainfall Warning in effect until 8:40 PM MDT.  Source: Environment Canada'
source = summary.match(regexFindSource);
console.log(source);

For your edit:

var source = wwArray.Source;   
var regexFindSource= new RegExp('(?:\S+\s)?\\S*: '+ source +'\S?');
var summary = 'Flash Flood Watch in effect until Friday, 2:00 AM EDT.  Rainfall Warning in effect until 8:40 PM MDT.  Source: Environment Canada'
source = summary.match(regexFindSource);
console.log(source);