3

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.

Ali Özen
  • 1,525
  • 2
  • 14
  • 29

2 Answers2

3

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");
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
0

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;
        }
Dilip
  • 474
  • 2
  • 8
  • 18