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?

4
  • 1
    You can't concatenate regex Commented Feb 24, 2016 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. Commented Feb 24, 2016 at 20:36
  • convert your string to a RegExp object stackoverflow.com/questions/4589587/… Commented Feb 24, 2016 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? Commented Feb 24, 2016 at 20:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
word = 'Joe/Hugh'?
well to be specific, when dynamic "word" catches Chris then how can I get Joe/Hugh/ with regex automatically afterwards ...
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; });
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.