I’m trying to match a string using regex that sometimes contains a forward slash in it it /.
This is an example string.
Armor Wars #1/2
But it could also be Armor Wars #1 or Armor Wars #25.2 or Armor Wars #5.NOW virtually anything can come after the #.
This is the code I have right now, but I can’t get it grab the full #1/2. It will just grab #1
const message = 'Armor Wars #1/2' // Try edit me
const issueNumber = message.match(/#\w+/)[0]
// Log to console
console.log(issueNumber)
I’ve tried various other patterns, but can’t figure out why it just keeps stopping at the slash.
>Solution :
You can use
/#\w+(?:[\/.]\w+)?/
See the regex demo.
Details:
#– a#char\w+– one or more letters, digits or underscores(?:[\/.]\w+)?– an optional sequence of[\/.]– a/or.\w+– one or more "word" chars
See the JavaScript demo:
const message = 'Armor Wars #1/2'
console.log( message.match(/#\w+(?:[\/.]\w+)?/)[0] ) // => #1/2