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?
Related Topics
JavaScript: Create and Use Arrays
Info | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
jQuery: Disable Submit Button if no Checkbox is selected
Tutorial | 7 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
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.
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:
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