var search_name = location.search;
if (search_name.search("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
});
If current document url is http://abc.com/list.html?cate_no=24,
I want to add class "active" into li a.
I searched and found these js code, but it doesn't work.
Is it wrong?
It's incorrect. search() returns the offset position of a match if a match is found, and -1 if a match isn't found.
As you are checking for whether cate_no=24 contains cate_no=24, it will return 0 if true.
Currently, your conditional checks whether the search() will return > 0, which is not what you want.
What you should be doing is check whether it is greater > -1:
if (search_name.search("cate_no=24") > -1)
Although, as I mentioned in the first revision of my answer, it would be better and faster to use indexOf() (search() is supposed to be used when dealing with regular expressions, not for simple string searches).
if (search_name.indexOf("cate_no=24") > -1)
search will only gives you the String. that will be in your case ?cate_no=24
So we leave the first part as it is and try to find the desired value in search_name as string.
var search_name = location.search;
This how we can find the index of the desired pattern.
if (search_name.indexOf("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
My personal blog is static so I also had to figure out how to do this without PHP or some other server side code.
This bit of code grabs the path of the current URL, e.g. if you are on http://example.com/about, it would return the string '/about/'. From there you write a simple conditional to add a class to the link you select.
var currentURL = window.location.pathname.toString();
console.log(currentURL);
if (currentURL = '/about/') {
$('a#about').addClass('active')
} else if (currentURL = '/work/') {
...
}
This could be further developed to grab the href attributes from an array of links with a certain class (.nav-items, for example) and add the active class to whichever element has a href equal to the returned string.
Related
I want to create a class for the title bars of pages that contain a certain piece of url.
My url is www.domainname.com/poste/XXX and I want to add the class only if the part after the .com contains only /poste/. I've seen examples for "contains this term" but it's not exactly what I'm looking for.
The existing class for the title bar is: .fusion-page-title-bar
Thanks in advance for the help and advice!
to check if a url contains any string, do the following:
if(window.location.href.indexOf(".com/poste") > -1) {
// do something
}
(checking if the index of a string is bigger than -1 is like asking if he is in there)
to conditonally add class:
element.classList.add("my-class");
combined it would be:
if(window.location.href.indexOf(".com/poste") > -1) {
titleClass = document.querySelector(".your-title-class");
titleClass.classList.add("conditionalClass");
}
*there are other solutions using jquery (like the one in #Wimanicesir comment), but it personaly prefer not using it :)
If I understand your problem is that you want to check if the URL ends with /poste/.
You can use the string function endsWith().
var url = window.location.href
console.log('Current url: ', url)
if (url.endsWith("js")) {
console.log('The url ends with js');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
I have a bunch of elements with names similar to "comp[1].Field" or "comp[3].AnotherField" where the index (1 or 3) changes. I'm trying to extract the index from the name.
Right now I'm using:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/)[1];
but I don't feel like this is the best way to do this.
Any suggestions?
Thanks
What you have is actually a pretty good way to do it, but you should add some checking that ensures that match() actually returns an array (meaning the string was found) and not null, otherwise you'll get a type error.
example:
var index = $(":input:last").attr("name").match(/\[(\d+)\]/);
if (match) { index = match[1]; }
else { /* no match */ }
I was wondering if it is necessary to check for the condition in this particular example.
The condition I'm talking about is if ( Id.indexOf("_") ).
It just checks to see if Id has an underscore and if so then set the variable to strip the underscore and replace with hyphen.
I know I can just use Id = Id.split("_").join("-"); without the if statement checking to see if the condition is true, but just wondering if in this case is it good practice to check for the condition first or not?
Which way would you do it? And explain why please.
Id = "My_ID";
var brand = "The Brand";
var b = brand.trim().toLowerCase();
var page = b.split(/\W+/g).join("-");
if ( Id.indexOf("_") ) {
Id = Id.split("_").join("-");
}
If there is no underscore your split() won't do anything, so no - there's no need for the if here. Go with something like that and you're fine:
Id = Id.split("_").join("-");
or
Id = Id.replace(/_/g, '-');
to avoid creating an array first.
This could answer your question:
console.log("mytext".split("_").join("-")); // mytext
console.log("my_text".split("_").join("-")); // my-text
furthermore condition in your code if (Id.indexOf("_")) does not work as you intended. You need to use if (Id.indexOf("_") > -1) or (~Id.indexOf("_"))
I want to check if a page contains a specific word. And if it doesn't contain the word, it should to some action.
I only have the code for checking if the word is contained.
var bodyText = document.body.textContent || document.body.innerText;
var msg = "My word";
if (bodyText.indexOf(msg) > -1) {
setTimeout(function() {
window.location = "http://contains.word";
}, 1000);
}
But I want to change it to if it NOT contains it. Any solution?
A simple lookup of the indexOf function should provide you the answer...
http://www.w3schools.com/jsref/jsref_indexof.asp
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
If that isn't clear, what you're looking for is if indexOf returns -1.
I know there are a lot of questions about this, but I didnt found exactly what I needed
This is the js I have
$j('.showCategory li a').each(function() {
var catId = $j(this).attr("data-id");
this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
});
This works great as it generate my url with the param I want. The problem is that if I click multiple times (this filter is available on all pages), it's adding the same parameter over and over, generating an url like this:
http://www.blabla.com/search?search=cat&filter_duration=short&filter_duration=medium&filter_duration=long
I tried fixing that by adding a condition like
$j('.showCategory li a').each(function() {
if(this.href.indexOf('filter_category') == -1) {
var catId = $j(this).attr("data-id");
this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
} else {
????
}
});
But in that case, it's not adding any parameter, but it's not replacing the value. How can I solve this please?
Use this pattern to do an in-place replacement with a regular expression:
} else {
this.href = this.href.replace(/filter_duration=(.+?)(&|$.*)()/, "filter_duration=" + catId + "$2"
}
This uses capture groups to find an existing filter_duration element query parameter, and replaces the existing value in place with a new value (in this case catId). This should work regardless of whether it is the last query parameter in the string or not.
That said, I wouldn't regard this solution as optimal, and you would probably be better off with storing the values that you want in your url in a client side javascript object, and then rebuild the url each time from scratch whenever anyone changes a category. That way you won't have to worry about difficult to test cases where something goes wrong with a replacement and the client getting into a bad state.