How to tell if a string contains a certain character in JavaScript?
With ES6 MDN docs .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E: Not suported by IE - instead you can use the Tilde opperator ~
(Bitwise NOT) with .indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
Used with a number, the Tilde operator effective does
~N => -(N+1)
. Use it with double negation !!
(Logical NOT) to convert the numbers in bools:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
If you have the text in variable foo
:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
This will test and make sure the user has entered at least one character, and has entered only alphanumeric characters.
To find "hello" in your_string
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
For the alpha numeric you can use a regular expression:
http://www.regular-expressions.info/javascript.html
Alpha Numeric Regular Expression
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }