bogdan
bogdan

Reputation: 667

How to test if url starts with a specific string in JS

I tried this, which I feel should have worked having read through a couple previous questions here:

$(function(){
    if(/tekstovi.test(window.location.href)) {
        $('#tekst').addClass('active');
    }
});

I want the element with ID #tekst to have the active class if the URL contains "/tekstovi"...

Upvotes: 0

Views: 885

Answers (2)

Dino
Dino

Reputation: 8292

You can first convert your URL into a variable. Then just check if that variable contains the substring you want with the indexOf() function.

It would look something like this:

var url = window.location.href;
if(url.indexOf('/tekstovi')){
  $('#tekst').addClass('active');
}

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

Just a backslash will do the trick, check this:

console.log(/\/tekstovi/.test("/tekstovi"));

If you want to check that window.location.href starts with /tekstovi, use this:

//checks if window.location.href starts with /tekstovi
console.log(/^\/tekstovi/.test("/tekstovi"));

//this will return false
console.log(/^\/tekstovi/.test("foo/tekstovi"));

Upvotes: 1

Related Questions