How to tell if a string contains a certain character in JavaScript?
How to tell if a string contains a certain character in JavaScript?
Question
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. I used maxlength
to limit the user to entering 24 characters.
The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.
How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?
Accepted Answer
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:
Read more... Read less...
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.
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }
ES6 contains inbuilt method (includes
) in String's prototype
, which can be used to check if string contains another string or not.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));
Following polyfill can be used to add this method in non-supported browsers. (Source)
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
Use a regular expression to accomplish this.
function isAlphanumeric( str ) {
return /^[0-9a-zA-Z]+$/.test(str);
}