3

Regex is so confusing to me. Can someone explain how to parse this url, so that I just get the number 7?

'/week/7'

var weekPath = window.location/path = '/week/7';
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
1
  • '/week/7'.split('/')[2] Commented Dec 21, 2015 at 18:53

4 Answers 4

6

Fixing your regex:

Add \/ to your regex as below. This will capture the / before and after the string week.

var weekPath = '/week/7';
var newString = weekPath.replace(/\/week\//,"");

console.dir(newString); // "7"

Alternative solution with .match():

To grab just the number at the end of the string with regex:

var weekPath = '/week/7';
var myNumber = weekPath.match(/\d+$/);// \d captures a number and + is for capturing 1 or more occurrences of the numbers

console.dir(myNumber[0]); // "7"

Read up:

Sign up to request clarification or add additional context in comments.

Comments

6

Place it as string and not regex

weekPath.replace("/week/","");
=> "7"

Difference ?

When the the string is delimited with / /, then the string is taken as a regex pattern, which will only replace week for you.

But when delimited by " ", it is taken as raw string, /week/

Comments

4
weekPath.replace(/week/,""); // trying to replace week but still left with //7/

Here you matched the characters week and replaced them, however your pattern doesn't match the slash characters. The two slashes in your source code are simply part of the syntax in JavaScript for creating a regex object.

Instead:

weekPath = weekPath.replace(/\/week\//, "");

Comments

2

You don't need to use regex for this. You can just get the pathname and split on the '/' character.

Assuming the url is http://localhost.com/week/7:

var path = window.location.pathname.split('/');
var num = path[1]; //7

Comments

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.