slapyo slapyo - 1 month ago 7x
Javascript Question

Javascript Regex Conditional

I have strings like this:

#WTK-56491650H #=> want to capture '56491650H'
#M123456 #=> want to capture 'M123456'

I want to match everything after the # unless there is a dash then I want everything after the dash. I have a feeling I'm close but maybe not. I've found a lot of stuff about javascript regex conditionals and I can never get it to do the if then else part. It only matches after the # and that's it.

This is what I have so far:


And the demo:


Here's a solution which uses non-capturing groups (?:stuff) which I prefer so I don't have to dig through the result groups to find the string I'm interested in.


First it throws out the # character, then throws out the stuff up to and including the - character, if it is there, then groups the rest as your match.