How can I check if one string contains another substring in JavaScript?
Usually I would expect a String.contains()
method, but there doesn't seem to be one.
Edit: thanks for all the answers :) However, it seems that I have another problem :(
When I use the ".indexof" method, Firefox refuses to start the JavaScript code (this is for an extension).
My code is:
var allLinks = content.document.getElementsByTagName("a");
for (var i=0, il=allLinks.length; i<il; i++) {
elm = allLinks[i];
var test = elm.getAttribute("class");
if (test.indexof("title") !=-1) {
alert(elm);
foundLinks++;
}
}
if (foundLinks === 0) {
alert("No title class found");
}
else {
alert("Found " + foundLinks + " title class");
}
Firefox doesn't display an alert box. This works if I get rid of the .indexof()
method. I already tried something like if (test=="title")...
, but it didn't work.
Source: Tips4all
var s = "foo";
ReplyDeletealert(s.indexOf("oo") != -1);
indexOf returns the position of the string in the other string. If not found, it will return -1.
https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Objects/String/indexOf
I know your question is already answered, but I thought this might be helpful too.
ReplyDeleteYou can easily add a contains method to String with this statement:
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
Note: see the comments below for a valid argument for not using this. My advice: use your own judgement.
The problem with your code is that Javascript is case sensitive. Your method call
ReplyDeleteindexof()
should actually be
indexOf()
Try fixing it and see if that helps:
if (test.indexOf("title") !=-1) {
alert(elm);
foundLinks++;
}
You could use the JavaScript search() method.
ReplyDeleteSyntax is: string.search(regexp)
It returns the position of the match, or -1 if no match is found.
See examples there: jsref_search
You don't need a complicated regular expression syntax. If you are not familiar with them a simple st.search("title") will do. If you want your test to be case insensitive, then you should do st.search(/title/i).
var index = haystack.indexOf(needle);
ReplyDeleteYou can use jQuery's ':contains' selector.
ReplyDelete$("div:contains('John')")
check it here: http://api.jquery.com/contains-selector/
You need to call indexOf with a capital "O" as mentioned. It should also be noted, that in JavaScript class is a reserved word, you need to use className to get this data attribute. The reason it's probably failing is because it's returning a null value. You can do the following to get your class value...
ReplyDeletevar test = elm.getAttribute("className");
//or
var test = elm.className
This just worked for me. It selects for strings that do not contain the term "Deleted:"
ReplyDeleteif (eventString.indexOf("Deleted:") == -1)
Use regular expression
ReplyDeleteRegExp.test(string)