Kahsn
Kahsn

Reputation: 1045

Get data from URL address

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?

Upvotes: 0

Views: 61

Answers (2)

Tuvia
Tuvia

Reputation: 869

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])

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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.

Upvotes: 0

Related Questions