-1

I'm trying to search for a specific string within URL and if the value is found, I want the script to return a page type.

I was using a simple indexOf, but it doesn't allow for RegEx & I can't seem to make this script work with using match.

I'm a newbie & any help is appreciated! :)

if ((window.location.href.indexOf("/czech-job-server/") > -1) || (window.location.href.indexOf("/prague/czech/") > -1)) {
   return("Detail");
}

else if (window.location.href.indexOf("jobs") > -1) {
   return("Category");
}

else {
   return("Page Not Defined");
}
  • could you put an example string input and output for us? – tfidelis Feb 17 '17 at 10:48
  • Can you add some more detail to this - if you tried to use `.match()`, how did you use it and what happened, can you show that code? Also see http://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex for examples – Pekka Feb 17 '17 at 10:49
  • Yes, I've tried match() instead indexOf -> e.g. window.location.href.match(job-server/g) > -1 Sadly I'm triggering the script through Google Tag Manager, so I don't have any other code to show you. It's just returning "undefined". – Luna Shirley Feb 17 '17 at 10:58

1 Answers1

0

well, i didn't see a pattern to use regex, so just put the word in an regex and call match. Match method returns an array of matches in current string:

var hrefString = window.location.href;

if ((hrefString.match(/czech-job-server/g).length > 0) || (hrefString.match(/prague\/czech/g).length > 0)) {

   return("Detail");
}

else if (hrefString.match(/jobs/g).length > -1) {
   return("Category");
}

else {
   return("Page Not Defined");
}
susanoobit
  • 128
  • 8
tfidelis
  • 443
  • 8
  • 16
  • Phew, it's finally working. I've just made a few changes to your code. Thank you :-). ---- function () { if ((window.location.href.match(/czech-job-server/g).length > 0) || (hrefString.match(/prague\/czech/g).length > 0)) { return("Detail"); } else if (window.location.href.match(/jobs/g).length > 0) { return("Category"); } else { return("Page Not Defined"); } } – Luna Shirley Feb 17 '17 at 11:11