0

I'm having trouble trying to use multiple back references in a javascript match so far I've got: -

function newIlluminate() {
  var string = "the time is a quarter to two";
  var param = "time";

   var re = new RegExp("(" + param + ")", "i");

    var test = new RegExp("(time)(quarter)(the)", "i");

  var matches = string.match(test);

  $("#debug").text(matches[1]);

}

newIlluminate();

#Debug when matching the Regex 're' prints 'time' which is the value of param.

I've seen match examples where multiple back references are used by wrapping the match in parenthesis however my match for (time)(quarter)... is returning null.

Where am I going wrong? Any help would be greatly appreciated!

3
  • 1
    Your regex test simply doesn't match the string (as it does not contain the substring timequarterthe). Do you want alternation? Commented Aug 17, 2013 at 13:24
  • what is the desired output? Commented Aug 17, 2013 at 13:25
  • Ideally I want to loop through the matches in the string and wrap each in a span. So I would expect matches[1] = time, matches[2] = quarter etc. Commented Aug 17, 2013 at 13:27

2 Answers 2

1

Your regex is literally looking for timequarterthe and splitting the match (if it finds one) into the three backreferences.

I think you mean this:

var test = /time|quarter|the/ig;
Sign up to request clarification or add additional context in comments.

2 Comments

That's because it's the first match. g changes the behaviour so that it returns all matches in the order they are found.
Yeah i figured that out seconds after my comment, had my head in this too long going nowhere thanks both! marked as answer because it was first :)
1

Your regex test simply doesn't match the string (as it does not contain the substring timequarterthe). I guess you want alternation:

var test = /time|quarter|the/ig; // does not even need a capturing group
var matches = string.match(test);

$("#debug").text(matches!=null ? matches.join(", ") : "did 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.