Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match string with numbers and forward slash in it using regex and javascript

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 #.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading