1

I have a function in jquery that returns the full URL. Based on that I assign active classes to the correct ID's. But one case tests if the word "fr" is in it (for the language button). But a lot of pages have names containing "frying".

So each time I go on a "frying" page the function gives the "fr" ID an active class.

Is there any way around it? Full url would be something like: www.example.com/frying/oils or in French: www.example.com/fr/frying/oils

$(function() {
  var loc = window.location.href; // returns the full URL 
    if(/fr/.test(loc)) {
    $('#fr').addClass('active');
    $('#en').removeClass('active');
    $('#nl').removeClass('active');
  }

});
jnb13
  • 63
  • 7

3 Answers3

1

You need a regex that matches the text "fr" between boundaries characters:

if(/\bfr\b/.test(loc)) {

}

You may also avoid regex, doing

if(loc.indexOf('/fr/') != -1) {

}
Alessandro
  • 1,443
  • 9
  • 18
1

if(/\/fr\//.test(loc)) { ought to do it. Check for the entire string that is the subdirectory, with the slashes.

Bob Brown
  • 1,463
  • 1
  • 12
  • 25
0

JavaScript/jQuery - How to check if a string contain specific words

Specific excerpt from it that might helpful:

function wordInString(s, word){
return new RegExp( '\\b' + word + '\\b', 'i').test(s);
}

This will match exact word case insensitive way...

Community
  • 1
  • 1
Girish Sakhare
  • 743
  • 7
  • 14