Greg Corliss
Greg Corliss

Reputation: 7

regular expression in javascript escaping backslash

I am trying to parse a portion of a url to include in a script using regex and the results are null. Not quite sure what I'm doing wrong. I've tried using regexr.com and it works fine there but doesn't seem to work in my code.

var url = window.location.href //this would return ..//path/##-###/something.aspx
var regex = /\d{2}-\d{3}/g
var projNumb = url.match(regex);
document.write(projNumb);

If I substitute a string with 12-234-567 in for the window.location.href it would return 34-567. Seems to have something to do with the "/" before the ## but if I escape the / like // javascript sees it as a comment.

End result, I'm trying to get 17-123 out of http://www.example.com/path1/path2/17-123/home.aspx and assign it to a variable for a query.

Upvotes: 0

Views: 274

Answers (1)

epascarello
epascarello

Reputation: 207501

Regular expression should start and end with the / and if you want to match a / than you need to escape it.

window.location.pathname.match(/\/(\d{2}-\d{3})\//)

Upvotes: 2

Related Questions