0

I have a website like below:

localhost:3000/D129/1

D129 is a document name which changes and 1 is section within a document. Those two values change depends on what user selects. How do I just extract D129 part from the URL using javascript?

Kahsn
  • 1,045
  • 3
  • 15
  • 25
  • Duplicates: [how to get the parameter from a url?](http://stackoverflow.com/questions/5321468/how-to-get-the-parameter-from-a-url) and [Last segment of URL](http://stackoverflow.com/questions/4758103/last-segment-of-url) and others... – Yogi Apr 18 '16 at 19:20

2 Answers2

1
window.location.pathname.match(/\/([a-zA-Z\d]*)/)[1]

^ that should get you the 1st string after the slash

var path = "localhost:3000/D129/1";

alert(path.match(/\/([a-zA-Z\d]*)/)[1])
Tuvia
  • 859
  • 4
  • 15
0

You can use .split() and [1]:

a = "localhost:3000/D129/1";
a = a.split("/");
alert(a[1]);

This works if your URLs always have the same format. Better to use RegEx. Wanted to answer in simple code. And if you have it with http:// or something, then:

a = "http://localhost:3000/D129/1";
a = a.split("/");
alert(a[3]);

ps: For the RegEx version, see Tuvia's answer.

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252