AnApprentice
AnApprentice

Reputation: 110960

How to determine if a string matches a pattern type

Given the following pattern types: where 11 and 22 are variable:

#/projects/11
#/projects/11/tasks/22

With Javascript/jQuery, given var url, how can I determine if var url equals either string 1, 2 or neither?

Thanks

Upvotes: 1

Views: 3434

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Here's a more flexible approach you can use for other urls too http://jsfiddle.net/EXRXE/

/*
  in: "#/cat/34/item/24"

  out: {
    cat: "34",
    item: "24"
  }
*/

function translateUrl(url) {
  // strip everytying from the beginning that's not a character
  url = url.replace(/^[^a-zA-Z]*/, "");
  var parts = url.split("/");
  var obj = {};
  for(var i=0; i < parts.length; i+=2) {
    obj[parts[i]] = parts[i+1]
  }
  return obj;
}

var url = translateUrl('#/projects/11/tasks/22');
console.log(url);

if (url.projects) {
   console.log("Project is " + url.projects);
}

if (url.tasks) {
    console.log("Task is " + url.tasks);
}

Upvotes: 0

Andy E
Andy E

Reputation: 344575

You can do it using a single regular expression:

var reg = /^#\/projects\/(\d+)(?:\/tasks\/(\d+))?$/,
    str = "#/projects/11/tasks/22",
    match = str.match(reg);

if (match && !match[2])
    // Match on string 1
else if (match && match[2])
    // Match on string 2
else
    // No match

The expression I wrote uses sub-expressions to capture the digits; the result would be an array that looks like this:

"#/projects/11/tasks/22".match(reg);
//-> ["#/projects/11/tasks/22", "11", "22"]

"#/projects/11".match(reg);
//-> ["#/projects/11", "11", undefined]

There are many regular expression tutorials online that will help you understand how to solve problems like this one - I'd recommend searching Google for such a tutorial.

Upvotes: 4

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

I would look into Regex personally, as it is easy to set up a pattern and test if a string applies to it. Try this: http://www.regular-expressions.info/javascript.html

Upvotes: 0

Related Questions