Ali Özen
Ali Özen

Reputation: 1609

How to get current url in jquery

I can't explain myself in title. What i want is get string between slashes. Like that: www.example.com/foo/bar/id/1 i want to get "foo". Because i made these codes.

select: function(event, ui) {
            if(window.location.href = "news/" + ui.item.slug){
           window.location.href =null;
            }
            else
                window.location.href ="news/" + ui.item.slug;
        }

I have a autocomplete search field. When i clicked a result, its redirecting me to www.example.com/news/34523 In this page if i use search field again, it redirects me to www.example.com/news/news/12412 After that i got 404. But if i am not in news tab, for example www.example.com/foo its working perfecly when i use search field. I just need an if statement, if i am in news pages act like another page.

Upvotes: 2

Views: 24753

Answers (4)

Anonymous
Anonymous

Reputation: 11

For A Url in jquery:

You Could Try The prop Method:

$(location).prop('href')

Or Try The attr Method:

$(location).attr('href')

Snippet:

function oneurl(){
alert($(location).prop('href'))
}
function twourl(){
alert($(location).attr('href'))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button onclick="oneurl()">#1</button>
<button onclick="twourl()">#2</button>

Upvotes: 1

Daniel
Daniel

Reputation: 1

You can get the current URL using the attr() method:

$(location).attr('href');

Upvotes: 0

Dilip
Dilip

Reputation: 483

The problem seems to be with your url that gets redirected. Try the below code.

select: function(event, ui) {
            if(window.location.href = "/news/" + ui.item.slug){

            }
            else
                window.location.href ="/news/" + ui.item.slug;
        }

Upvotes: 0

Luca Kiebel
Luca Kiebel

Reputation: 10096

You could simply use the location.pathname property to get the part between the first and second slash and run code based on this.

console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");

To show that this works, here is another snippet, acting as if url was window.location:

let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";

console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");

Upvotes: 4

Related Questions