0

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.

2
  • 1
    var regex = /\d{2}-\d{3} is not valid... typo writing the question? Commented Mar 22, 2017 at 15:57
  • Yeah, left out the /g will edit to fix. With the /g it works fine in regexr.com Commented Mar 22, 2017 at 16:02

1 Answer 1

2

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})\//)
Sign up to request clarification or add additional context in comments.

9 Comments

The example URL you gave, this code works. What is the problem? var match = url.match(/\/(\d{2}-\d{3})\//); if(match) { console.log(match[1]); }
What is the path that is failing? console.log(window.location.pathname) And so you realize it returns an array?
Sorry having issues getting code to format in comments. Feel like an idiot. I'm indenting 4 spaces but doing nothing. Still returning null. If I assign window.location.pathname to a variable and use document write it writes out as expected. As soon as I attach the .match(/\/(\d{2}-\d{3})\//) it returns null. I tried this also in codepen just using a variable with a string like the example url and it returns 2 values "/17-123/,17-123"
So what is the pathname? Formatting surround code with ` on each side, there is no code blocks in comments
I put in: var projnumb = window.location.pathname.match(/\/(d{2}-\d{3})\//); document.write(projnumb); I get null as a return value. If I put in the following: var projnumb = window.location.pathname; document.write(projnumb); I get a pathname: /air/52/AVMI/529/projects/Proj-Office/site-templates/01-001/default.aspx
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.