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.
Related
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'm obtaining a list of elements in classes and I'd like to filter out any class which does not contain a specific word in the innerHTML. Currently, I've managed to filter out the words however I can't seem to obtain the whole string, only part of it. Here's what I've got:
htmlData = $(htmlData).find(".Description").html("Fruit");
All this does is return "FruitFruitFruitFruitFruit..." when I'd like to obtain the whole string which the word is in. Anyone know how to do it? Thanks.
Wrap the assignment in an if, in which you're checking if the string is contained in the Text.
if($(htmlData).find(".Description").text().indexOf("Fruit") === -1){
htmlData = $(htmlData).find(".Description").html();
}
the indexOf function returns the index of where the string was found first. If it wasn't found, it returns -1.
I hope that this is what you meant..
var arr = [];
$.each($(htmlData).find(".Description"), function(_, jqElem){
var content = jqElem.html();
if (content.indexOf("Fruit") !== -1 ) {
arr.push(content);
}
})
I have a Chrome extension that replaces certain phrases on webpages. It uses a 2 dimensional array. The [i][1] replaces the text in provided in the [i][0] value.
for (var i = 0; i < array.length; i++) {
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: array[i][0],
replace: array[i][1]
});
}
This code works fine yet it seems computationally expensive as it calls the findAndReplaceDOMText function multiple times rather than just once. Is it possible to move the for loop inside the function to just wrap the find and replace params? If so what would that look like? I can only get console errors trying this.
Edit: The function traverses the DOM looking for all visible human readable text that contains the regex phrase provided at find and replaces with the string provided at replace.
Without modifying the function's behaviour, you can't. What you could do is separating the find and replace passes.
Your strings are stored in a kind of difficult to transverse way, so let's flat them out:
var flatFind = array.map(function(elem){
return elem[0]
})
var flatReplace = array.map(function(elem){
return elem[1]
})
Then, you'd need to create a regex string that encompasses all your search strings:
var searchString = "/("+flatFind.join("|")+")/g"
Then pass it to the function, using a function to find the index of the match:
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: searchString,
replace: function(portion, match){
var idx = flatFind.indexOf(match)
if(idx > -1) return flatReplace[idx]
else throw "hey, there's no replacement string for this!"
}
})
You could try to use the replace parameter as a function.
The find-configuration-property then needs to be a regular expression (RegExp-object) constructed of your search strings (like /first|second|third/g). Do not forget the g-modifier at the end.
As replace-configuration-property you then create a function that checks which string occurred (you get that as the second parameter to your function). According to the match you then return the corresponding value (for example if match is "first" then you return "1st". If match is "second" then you return "2nd" and so on).
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.
How would our group find out if a particular string contains a certain substring? Only with the help of jquery, please.
You don't really need jQuery for such a simple thing, you can simply use the indexOf method of String objects, e.g.:
var str = "foobar";
var containsFoo = str.indexOf('foo') >= 0; // true
The indexOf method returns the character index where the first occurrence of the specified value is encountered, if not found, it returns -1.
Why use 10 characters when 100 will do?
Here's the requested jQuery plugin:
jQuery.isSubstring = function(haystack, needle) {
return haystack.indexOf(needle) !== -1;
};
Usage:
$.isSubstring("hello world", "world")); // true;
If your limited to jQuery which is just JavaScript... you can use the filter
var subgtSel = $("#jquerySelector").filter(function(i) {
// do your filter here
return $(this).attr("data-timestamp") <= subMsg.CreateDateTimeStamp;
});
the subgtSel becomes your new jQuery now with the relevant filter in the above. In the above, I am looking for all div elements that have an attribute that is less than the subMsg.CreateTimeStamp.
If your looking for a particular substring... you can do the following with jQuery right in the selector
var sel = $("#jquerySelector:contains('text')");
see http://api.jquery.com/contains-selector/