Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13412

Use regex to parse this string?

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/

Upvotes: 3

Views: 74

Answers (4)

Rahul Desai
Rahul Desai

Reputation: 15501

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:

Upvotes: 6

JNYRanger
JNYRanger

Reputation: 7097

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

Upvotes: 2

dsh
dsh

Reputation: 12214

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\//, "");

Upvotes: 4

nu11p01n73R
nu11p01n73R

Reputation: 26667

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/

Upvotes: 6

Related Questions