Kostas Koutoupis
Kostas Koutoupis

Reputation: 93

Combine two regular expressions in Javascript

I need a regular expression that picks up the author in the following scenarios

Letter from author to recipient regarding topic 11-10-2018

Letter from author, regarding topic 10-11-2018

I tried following the suggestions found here and this is what i have:

let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
let combinedRegex = new RegExp(commaRegex + '|' + fromToRegex);
let author = document.getElementById('userInput').value.match(combinedRegex);
console.log(author) 

But the console.log(author) returns 'null'.

I am using this on Chrome as look behinds are not supported in all browsers. Any suggestions?

Upvotes: 1

Views: 686

Answers (2)

dquijada
dquijada

Reputation: 1699

Apart from the solution provided by georg, just in case you want to combine any other two that aren't as easily substituted by one:

You have to add the sources instead of the whole object:

let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
let combinedRegex = new RegExp(commaRegex.source + '|' + fromToRegex.source);

let sampleText = 'Letter from Joseph Tribbiani to recipient regarding topic 11-10-2018';

console.log(sampleText.match(combinedRegex));

sampleText = 'Letter from Joseph Tribbiani, regarding topic 11-10-2018';

console.log(sampleText.match(combinedRegex));

Upvotes: 1

georg
georg

Reputation: 214959

There's no need to combine them "automatically", just use the or operator for the last part:

(?<=from )(.+?)(?=,| to)

https://regex101.com/r/xzlptd/2/

To make it work in all browsers, get rid of the look-arounds

from (.+?)(?:,| to)

and pick the first group from the match: .match(...)[1]

Upvotes: 3

Related Questions