Regular Expression Routing with Iron-router

I am trying to write a route with an iron router for a meteor to catch all requests:

  • / game / Quarterfinal3
  • / game / Semifinal5
  • / game / Grandfinal1

etc .. This is what I tried, but it doesn't work ...

Router.route('final', {path: "(\\/)(game)(\\/).*?(final)(\\d)"}, function() {
  console.log("final");
  this.render('notStartedGame');
});

      

How to solve this?

+3


source to share


2 answers


You don't need a regex in your path as long as you use the format :pathParam

in your paths and it will be available within this.params.pathParam

, namely:

if you are trying to catch these three routes:

Router.route('/game/:gameName', function() {
  var acceptablePaths = ["Quarterfinal3", "Semifinal5", "Grandfinal1"],
      gameName = this.params.gameName;
  // check if the game name is one of those that we are looking for
  if ( _.contains(acceptablePath, gameName) ) this.render("notStartedGame");
  // otherwise render a not found template or if you want do something else
  this.render("gameNotFound"); //assuming you have such a template
});

      



or if you are looking for some route that contains "final" in it:

Router.route('/game/:gameName', function() {
  var checkFor = "final",
      gameName = this.params.gameName;
  // check if the game name includes "final"
  if ( gameName.indexOf(checkFor) > -1 ) this.render("notStartedGame");
  // otherwise render a not found template or if you want do something else
  this.render("gameNotFound"); //assuming you have such a template
});

      

+3


source


In the future (since Meteor might do exactly what you asked), the DontVoteMeDown comment was right there.

The following route has a fixed part /game

followed /:gameName

by a regex-based named parameter .*final\d+

.

Router.route('/game/:gameName(.*final\\d+)', function() {
      console.log(this.params.gameName);
})

      



Nice to note:

  • You don't need to use one regex all the way. You can use regular expressions somewhat localized, bound to the fixed part, for example /fix1/(.*)/fix2/:reg2(.*)/

    . Check out the very nice documentation on the way to regex .

  • You don't have to worry about paths that don't match the regex - they won't break at all.

  • Remember to properly escape your regexes (e.g. note the double backslash)

0


source







All Articles