445

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?

Dov Miller
  • 1,958
  • 5
  • 34
  • 46
Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 2
    The answer found here http://stackoverflow.com/questions/3192612 has the information on how to validate on alphanumeric. – JasCav Dec 14 '10 at 21:39
  • 1
    And to learn regular expressions: http://www.regular-expressions.info – Felix Kling Dec 14 '10 at 21:42
  • For you jquery folks you should and could use `inArray`. – JonH Apr 24 '12 at 14:55
  • 3
    How input is formatted is not a human's problem. It's the computer's problem. Take whatever the user enters and remove all the characters that don't belong (non-alpha), test to see the result is 24 characters long, then validate it. User's really hate formatted input. – tggagne Oct 19 '13 at 16:15

20 Answers20

714

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

Community
  • 1
  • 1
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • That was quite helpful. Speaking as a python programmer, I am using that to replace the "in" keyword (which may or may not be unorthodox, I am unsure) but it works for more than just a single character. – trevorKirkby Dec 29 '14 at 05:43
  • 1
    I don't understand how this was voted at the answer. I can see that a lot of people come here by Googling. A better way would definitely be using a regular expression. – Spock Oct 13 '15 at 18:32
  • 36
    You would use a regular expression to check for a single character? That's an excessive amount of overhead to get the exact same thing the built in function does. There are a lot of people who don't understand regex, and generally the simpler answer is the best. – kemiller2002 Oct 13 '15 at 19:19
  • I would go with `/hello/g.test(your_string)`. While indexOf works, I think a regex test tells a better story of what you're trying to accomplish. If I'm trying to find a sequence of characters inside a string, the index is irrelevant. – Joe Maffei Feb 22 '17 at 21:49
  • [Docs for indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) – cgaldiolo May 24 '18 at 13:14
137

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

 
domster
  • 556
  • 2
  • 8
  • 26
julian libor
  • 1,583
  • 1
  • 9
  • 8
71

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
20

check if string(word/sentence...) contains specific word/character

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • Does it works on IE?--> http://stackoverflow.com/questions/3480771/jquery-how-to-see-if-string-contains-substring – Ger Soto Apr 11 '13 at 09:27
15

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;
    }
  };
}
Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
10

You're all thinking too hard. Just use a simple Regular Expression, it's your best friend.

var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."

var regex = /(pizza)/g // Insert whatever phrase or character you want to find

string1.test(regex); // => true
string2.test(regex); // => false

Learn Regex in 5 minutes?

Adam McArthur
  • 950
  • 1
  • 13
  • 27
8

Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
6

var inputString = "this is home";
var findme = "home";

if ( inputString.indexOf(findme) > -1 ) {
    alert( "found it" );
} else {
    alert( "not found" );
}
Aman Maurya
  • 1,305
  • 12
  • 26
6

If you're searching for character(s) in the start or at the end of the string, you can also use startsWith and endsWith

const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true
Ejaz Karim
  • 3,676
  • 6
  • 36
  • 49
5

Kevins answer is correct but it requires a "magic" number as follows:

var containsChar = s.indexOf(somechar) !== -1;

In that case you need to know that -1 stands for not found. I think that a bit better version would be:

var containsChar = s.indexOf(somechar) >= 0;
Taki
  • 17,320
  • 4
  • 26
  • 47
Mika Karjunen
  • 342
  • 4
  • 9
  • Well according to the [original](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf#page=83), [current](http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.indexof), and [draft](https://tc39.github.io/ecma262/#sec-string.prototype.indexof) standards, `indexOf()` will return *-1* if the string is not found. So it's hardly more *magic* than using *0*. – Uyghur Lives Matter Mar 30 '16 at 18:25
5

To test for alphanumeric characters only:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).

fairfieldt
  • 861
  • 1
  • 6
  • 10
4

Try this:

if ('Hello, World!'.indexOf('orl') !== -1)
    alert("The string 'Hello World' contains the substring 'orl'!");
else
    alert("The string 'Hello World' does not contain the substring 'orl'!");

Here is an example: http://jsfiddle.net/oliverni/cb8xw/

Oliver Ni
  • 2,606
  • 7
  • 29
  • 44
4

String's search function is useful too. It searches for a character as well as a sub_string in a given string.

'apple'.search('pl') returns 2

'apple'.search('x') return -1

learner010
  • 445
  • 5
  • 17
4

If you are reading data from the DOM such as a p or h1 tag, for example, you will want to use two native JavaScript functions, it is quiet easy but limited to es6, at least for the solution I am going to provide. I will search all p tags within the DOM, if the text contains a "T" the entire paragraph will be removed. I hope this little example helps someone out!

HTML

<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>

JS

let paras = document.querySelectorAll('p');

paras.forEach(p => {
  if(p.textContent.includes('T')){
       p.remove();
    } 
});
4

You can use string.includes(). Example:

var string = "lorem ipsum hello world";
var include = "world";
var a = document.getElementById("a");

if (string.includes(include)) {  
  alert("found '" + include + "' in your string");
  a.innerHTML = "found '" + include + "' in your string";
}
<p id="a"></p>
ArcadeSmasher
  • 145
  • 1
  • 10
2

Working perfectly.This exmple will help alot.

<script>    
    function check()
    {
       var val = frm1.uname.value;
       //alert(val);
       if (val.indexOf("@") > 0)
       {
          alert ("email");
          document.getElementById('isEmail1').value = true;
          //alert( document.getElementById('isEmail1').value);
       }else {
          alert("usernam");
          document.getElementById('isEmail1').value = false;
          //alert( document.getElementById('isEmail1').value);
       }
    }
</script>

<body>
    <h1>My form </h1>
    <form action="v1.0/user/login" method="post" id = "frm1">
        <p>
            UserName : <input type="text" id = "uname" name="username" />
        </p>
        <p>
            Password : <input type="text" name="password" />
        </p>
        <p>
            <input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
        </p>
        <input type="submit" id = "submit" value="Add User" onclick="return check();"/>
    </form>
</body>
chriz
  • 1,339
  • 2
  • 16
  • 32
MankitaP
  • 57
  • 1
  • 1
  • 7
2

A sample regex pattern test you can use to find out if the string contains a character '@':

/(@[A-Za-z])\w+/.test(str_text)

shasi kanth
  • 6,987
  • 24
  • 106
  • 158
0

Check if string is alphanumeric or alphanumeric + some allowed chars

The fastest alphanumeric method is likely as mentioned at: Best way to alphanumeric check in Javascript as it operates on number ranges directly.

Then, to allow a few other extra chars sanely we can just put them in a Set for fast lookup.

I believe that this implementation will deal with surrogate pairs correctly correctly.

#!/usr/bin/env node

const assert = require('assert');

const char_is_alphanumeric = function(c) {
  let code = c.codePointAt(0);
  return (
    // 0-9
    (code > 47 && code < 58) ||
    // A-Z
    (code > 64 && code < 91) ||
    // a-z
    (code > 96 && code < 123)
  )
}

const is_alphanumeric = function (str) {
  for (let c of str) {
    if (!char_is_alphanumeric(c)) {
      return false;
    }
  }
  return true;
};

// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
  for (let c of str) {
    if (
      !char_is_alphanumeric(c) &&
      !is_almost_alphanumeric.almost_chars.has(c)
    ) {
      return false;
    }
  }
  return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);

assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('你好'));

assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('你好'));

GitHub upstream.

Tested in Node.js v10.15.1.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
0

It's worked to me!

Attribute Contains Selector [name*=”value”]

This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.

source: Attribute Contains Selector [name*=”value”] => https://api.jquery.com/attribute-contains-selector/

 <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attributeContains demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
 
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
 
</body>
</html>
Caique Andrade
  • 1,025
  • 7
  • 9
0

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

know more

MD SHAYON
  • 7,001
  • 45
  • 38