Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a string contains a certain character in JavaScript?

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?

like image 331
Vivian River Avatar asked Dec 14 '10 21:12

Vivian River


People also ask

How do you check if a string contains a certain word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do I check if a string contains one character?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How do you check if a string does not contain a character in JavaScript?

To check if a string doesn't include a substring, call to the indexOf() method on the string, passing it the substring as a parameter. If the indexOf method returns -1 , then the substring is not contained in the string.

How do you check if a substring exists in a string JavaScript?

To check if a substring is contained in a JavaScript string:Call the indexOf method on the string, passing it the substring as a parameter - string. indexOf(substring) Conditionally check if the returned value is not equal to -1. If the returned value is not equal to -1 , the string contains the substring.


1 Answers

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

like image 89
kemiller2002 Avatar answered Sep 19 '22 08:09

kemiller2002