0

I want to match /events/:eventId or /events/:eventId/ with regex. :eventId can be any alphanumeric string.

This is what I have at the moment

str.match(/events\/[A-Za-z0-9]+\/?/)

How can I make sure it doesn't match something like:

/events/das873jh/image

Update

For some reason, this code matches but puts random characters like a , at the end of the string when there's a match. Why?!

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var str = "/events/ji893u"; 
  var res = str.match(/^\/events\/[a-zA-Z0-9]+(\/)?$/);
  document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Anchors, `^` and `$`. Use `/^events\/[A-Za-z0-9]+\/?$/` – Wiktor Stribiżew Jan 18 '19 at 23:03
  • https://regex101.com/ Tons of regex testing sites out there. Or, you know, *try it* and see – Taplar Jan 18 '19 at 23:03
  • `/^\/events\/[a-zA-Z0-9]+(\/)?$/` would most likely do it – Taplar Jan 18 '19 at 23:06
  • @Taplar Thanks but it doesn't seem to like the `^$` when I try it with javascript's match() – Tometoyou Jan 18 '19 at 23:08
  • http://jsfiddle.net/umy8wtx9/ you may want to use test, if you are expecting a boolean that is. – Taplar Jan 18 '19 at 23:09
  • @Taplar test didn't seem to work, try my code snippet, there's something weird where it adds a `,` at the end of my matched string. – Tometoyou Jan 18 '19 at 23:15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match `match()` returns an array of the substrings that match your regex. And you are adding that array to your html. Most likely the comma is coming from the to string of the array. Rather than adding it to the html, console log it – Taplar Jan 18 '19 at 23:18
  • Does the pattern have to be the entire line? If not you don't need the anchor or end on line. The patterns I see above wont match the colons either. Try `\/events\/\:[A-Za-z0-9]{1,}\/?` – stever Jan 18 '19 at 23:27
  • @stever `:eventId` is a place holder for a variable, unless I'm reading it wrong, so it will not contain a `:`. Also your regex would require the string to end with a `/`, which the OP says is optional. – Taplar Jan 18 '19 at 23:29
  • It matches both. The "?" makes the last `/` optional. I thought it was a route rather than a placeholder. I'm using Sublime3 to test. I love these exercises. Not saying I'm good at them, just that they're fun! – stever Jan 18 '19 at 23:34
  • 1
    Ah, I confused the last `/` as the regex closure. herp derp – Taplar Jan 18 '19 at 23:34
  • My bad. It IS a js question. – stever Jan 18 '19 at 23:36

0 Answers0