2
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?

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
lowdegeneration
  • 359
  • 5
  • 13
  • 1
    You can't concatenate regex – Amit Feb 24 '16 at 20:34
  • Don't attempt to use the value of a variable until it has been assigned. And regex literals don't work like this. – Oriol Feb 24 '16 at 20:36
  • convert your string to a RegExp object http://stackoverflow.com/questions/4589587/javascript-regular-expression-string-to-regex-object – phenxd Feb 24 '16 at 20:41
  • Are you just trying to match "home"? Whats wrong with `/home/`? is it that you want to use a variable to make the regexp? – Gabs00 Feb 24 '16 at 20:41

2 Answers2

1

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.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • I also a need pattern to catch "car/home/" or Joe/Hugh/...I mean I also need to catch 2 "/" with 2 words. How can I define it like "/" repeated 2 times and then get the words together. – lowdegeneration Feb 24 '16 at 22:26
  • `word = 'Joe/Hugh'`? – Oriol Feb 24 '16 at 22:37
  • well to be specific, when dynamic "word" catches Chris then how can I get Joe/Hugh/ with regex automatically afterwards ... – lowdegeneration Feb 24 '16 at 22:41
  • Consider not using regex: `var wordsString = "car/home/pencil,Joe/Hugh/Jack/Chris", word = 'home', matched = wordsString.split(',').filter(function(str){ return str.split('/').indexOf(word) >= 0; });` – Oriol Feb 24 '16 at 23:05
0

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
Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68