Reputation: 6555
I have a URL that looks like....
/page/sub/25/ --- edit page with ID @%
/page/sub ---new page has no ID
The last part of the URL is always the ID (if its not a new page then there is not ID).
I need in jQuery to get the last part of the URL and send it with the POST. For example...
$.ajax(
{
type: "POST",
url: URLVar,
data: "site="+encodeURIComponent(JSON.stringify(site)),
dataType: "json",
},
Where URLVar
if it has ID is would be
page/update/25
and if not
/page/update
How can I generate URLVar based on the current URL do this?
Upvotes: 0
Views: 70
Reputation: 38345
Personally I'd use a regular expression to search for a number, followed by a /
, at the end of the string; then form the update URL based on whether or not that matches. You can split that logic out into a function, like so:
function getUpdateUrl(url) {
var matches = url.match(/(\d+)\/$/);
return '/page/update' + (matches ? '/' + matches[1] : '');
}
Then, for example, you'd call it like so:
console.log(getUpdateUrl('/page/sub/')); // outputs /page/update
console.log(getUpdateUrl('/page/sub/25/')); // outputs /page/update/25
In your case, you'd probably want to call getUpdateUrl(window.location.href)
.
Upvotes: 1
Reputation: 73966
Try this:
var href = window.location.href;
var val = href.substr(href.lastIndexOf('sub') + 4).replace('/', '');
var URLVar = '';
if (val !== '') URLVar = 'page/update/' + val;
else URLVar = '/page/update';
alert(URLVar);
Upvotes: 1
Reputation: 122026
try
var url = location.href;
var id= url.substring(url.lastIndexOf('/') + 1);
Upvotes: 1