Steve Kim
Steve Kim

Reputation: 5611

lastIndexOf for URL

So, I have the following script:

<script>
   var id = window.location.href
   var buttonText = id.substr(id.lastIndexOf('/') + 1);
   jQuery("#first_button").html(buttonText)
</script>

So, what it does is that it replaces text of "id=first_button" button with the url next to the last "/".

Here is the set up of URL for my site: mysite.com/first/second/

The problem is that, all my pages end with "/" (ex. .com/something/something/something/).

So, the nothing shows up as there is nothing after the last "/"

Here is what I am trying to achieve essentially.

I have two buttons: First button and Second Button.

And the URl of any pages will follow the same format: `.com/first/second/.

I am trying to replace the first button with /first/ URL and second button with /second/ URL as shown below.

enter image description here

In summary, the code that I have right now only changes the first button text by the URL after the last "/".

I want the URL between first and second "/" (such as ".com/first/") to replace the first button title.

I want the URL between the second and third "/" (such as".com/first/second/") to replace the second button.

In jQuery, how can I target the specific URL section?

Thanks bunch!

Upvotes: 2

Views: 339

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382454

You seem to want this :

var parts = window.location.href.split('/').filter(Boolean);
jQuery("#second_button").html(parts.pop());
jQuery("#first_button").html(parts.pop());

split('/') makes an array from the href, pop() takes the last element of that array.

You can also do it with a regular expression:

var m = window.location.href.match(/([^\/]+)\/([^\/]+)\/?$/);
if (m) {
    jQuery("#first_button").html(m[1]);
    jQuery("#second_button").html(m[2]);
}

If you don't want the two last parts of the href but the two first parts of the path, do it like this:

var m = window.location.pathname.match(/([^\/]+)\/([^\/]+)/);
if (m) {
    jQuery("#first_button").html(m[1]);
    jQuery("#second_button").html(m[2]);
}

Upvotes: 2

Related Questions