lowdegeneration
lowdegeneration

Reputation: 379

multiple regex match using javascript

var wordsString="car/home/pencil,Joe/Hugh/Jack/Chris";
var word='home';
var pattern1=/^/+word;
var pattern2=/,/+word;
var pattern3 =/\//+word;

var matched = wordsString.match(pattern1+ /|/ +pattern2+ /|/ + pattern3 + /g/);

I want to match results from wordsString by using pattern1, pattern2, pattern3.

I need to match according to pattern1 or pattern2 or pattern3. But I get null.

Where is the problem?

Upvotes: 2

Views: 6203

Answers (2)

Oriol
Oriol

Reputation: 288000

You can't concatenate regexp literals. However, you can concatenate strings and use them to build a regexp object:

var wordsString = "car/home/pencil,Joe/Hugh/Jack/Chris",
    word = 'home',
    escapedWord = RegExp.escape(word),
    patterns = ['^' + escapedWord, ',' + escapedWord, '/' + escapedWord],
    regex = new RegExp(patterns.join('|'), 'g'),
    matched = wordsString.match(regex);

RegExp.escape is needed in case word contains characters with special meaning in regular expressions. It has been proposed as a standard but has not been accepted yet, so you must define it manually using the code from here.

Upvotes: 1

Chris Hawkes
Chris Hawkes

Reputation: 12410

You cannot concatenate Regex's in JavaScript the way you are doing it, but you can concat strings that comprise a single regex. Don't escape the pipe symbol though, that is how it matches this or that.

var one = "test"
var two = "this"

var regex = new RegExp("^(first|" + one + "|" + two + ")")

var match = regex.test("this"); // matches
var noMatch = regex.test("no match"); // does not match

Upvotes: 0

Related Questions