Da Silva
Da Silva

Reputation: 229

get value from the url

I have a url in the formathttp://localhost:8080/testURL/location/#/old/Ds~1016,

The value 1016 will change based on the page selected.. is it possible in javascript to get the number 1016 part from url(based on page selected)???

Ive tried the function

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);

var results = regex.exec(window.location.search);
if (results == null)
    return "";
else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

Upvotes: 1

Views: 198

Answers (4)

Jacob George
Jacob George

Reputation: 2627

You could also try it this way

window.location.href.split('~').pop(-1)

that should give you "1016"

Although the following would be better

window.location.href.split('/').pop(-1).split('~').pop(-1)

to make sure it is the last "/" element you are splitting

UPDATE

I always prefer using split() if it is for a single condition because the code is more understandable even though regex give better performance in the longer run. You can check the performance of regex vs split here

Upvotes: 2

Jashwant
Jashwant

Reputation: 29025

window.location.hash.split('~')[1]

Explanation:

We first grab the hash i.e. #/old/Ds~1016 by window.location.hash

Now, we split the hash with ~ (I assume that comes only one time in url)

split returns an array with Ds at 0th index and 1016 at 1st index.

So, finally

window.location.hash.split('~')[1] returns `1016`

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

I guess you can use the built-in window.location. And without regex you can do:

a = "http://localhost:8080/testURL/location/#/old/Ds~1016";
a.substring(a.indexOf("~")+1); // 1016

Or in a simpler way, you can use this:

window.location.hash.split('~')[1]

You can see the fiddle here: http://jsfiddle.net/DqzQF/

Feel free to try out all the URLs.

Upvotes: 2

Marcus
Marcus

Reputation: 6849

Try this:

regex = new RegExp("[0-9]*$");
regex.exec(window.location.hash);

To get the number, just use regex.exec(window.location.hash)[0], and then you may need to check whether it is 4 digits width.

Upvotes: 2

Related Questions