7

I have a ASP.NET website that is URL-Rewriting enabled. I know how to get route parameters using C#:

Page.RouteData.Values["id"] as string;

But I don't know how to get it from javascript? Following is my rewritten link format:

http://www.domain.com/topic/{id}/{title}

I want to get this {id} field using JavaScript. Please help!

UPDATE

I have this code that gets request parameter.

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

How can this be modified to get route parameter?

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107

2 Answers2

7
function getValueAtIndex(index){
    var str = "http://www.sample.com/234/Fiddle/test"; //window.location.href; 
    return str.split("/")[index];
}
console.log(getValueAtIndex(3));

Update

Here's a much cleaner way of getting value at an index in the route using plain JS:

    location.pathname.split('/')[index]
    

For example, for the current page,

location.pathname = '/questions/20302776/how-to-get-route-parameter'

You can get the question id by doing:

location.pathname.split('/')[2]

// Notice that the index does not start from zero.
Vikram Deshmukh
  • 12,304
  • 4
  • 36
  • 38
  • this kinda sucks if working with a virtual directory. – Mike Jul 31 '17 at 16:58
  • 1
    I like this but split the string into a separate array variable and then use the arrays length - the supplied index - 1 as the array index. That way it works backwards so 'test' is returned for index 0, 'Fiddle' for index 1 etc. This would solve the problem of virtual directories. – Kate Oct 17 '17 at 13:12
1

Try the following:

const getRouteValueAt = (idx) => {

   const routeTokens = location.pathname.replace(/^\/+/g,'').split('/')
   //[questions,20302776,how-to-get-route-parameter-in-javascript]

   return routeTokens.length > idx ? routeTokens[idx] : undefined
}

Usage

const routeName = getRouteValueAt(0); // questions
const routeId = getRouteValueAt(1); // 20302776
Ali Kleit
  • 3,069
  • 2
  • 23
  • 39