00 Votes

JavaScript: Is String containing another String?

Question by Chematik | Last update on 2021-01-13 | Created on 2012-08-07

I want to test, whether a string contains another string in JavaScript. So far, I've tried it with String.contains(), but that seems not to work somehow.

Does anyone have a solution?

ReplyPositiveNegative
00 Votes

In JavaScript, the function contains() in relation to strings can not be used in this way. You need the function indexOf(), which you can use something like this:

var str = "ABCDEF";
 
if (str.indexOf("CDE") != -1) {
   alert('The string contains "CDE".');
} else {
   alert('The string does not contain "CDE".');
}

As a parameter, you pass the string, you would like to search for. In the example above, this is "CDE". The function then gives us the position of the passed string, or -1, if there is no position, so therefore, the string is not included.

In our example, "CDE" is included in "ABCDEF". This would make the IF condition not -1 and 'The string contains "CDE".' would be the alert.

Important: Make sure, that you also write "indexOf" and not "indexof". Otherwise it is not working.
Last update on 2021-01-13 | Created on 2012-08-07

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.