How do you check if a word contains a letter 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?

Dov Miller

1,8685 gold badges34 silver badges44 bronze badges

asked Dec 14, 2010 at 21:35

How do you check if a word contains a letter in javascript?

Vivian RiverVivian River

30.3k60 gold badges190 silver badges305 bronze badges

4

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

5362 gold badges8 silver badges23 bronze badges

answered Jun 15, 2017 at 22:26

3

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.

answered Dec 14, 2010 at 21:38

cdhowiecdhowie

149k23 gold badges278 silver badges290 bronze badges

0

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

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 

answered Apr 11, 2013 at 7:02

How do you check if a word contains a letter in javascript?

T.ToduaT.Todua

50.1k19 gold badges217 silver badges213 bronze badges

1

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;
    }
  };
}

answered Dec 3, 2017 at 9:55

How do you check if a word contains a letter in javascript?

Vipin KumarVipin Kumar

6,3231 gold badge17 silver badges25 bronze badges

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?

answered Oct 3, 2014 at 14:44

How do you check if a word contains a letter in javascript?

Adam McArthurAdam McArthur

9201 gold badge13 silver badges25 bronze badges

5

Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}

answered Dec 14, 2010 at 21:41

Gabriele PetrioliGabriele Petrioli

185k34 gold badges254 silver badges306 bronze badges

2

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

answered Jul 13, 2018 at 13:49

How do you check if a word contains a letter in javascript?

Ejaz KarimEjaz Karim

3,6466 gold badges36 silver badges49 bronze badges

0

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

if ( inputString.indexOf(findme) > -1 ) {
    alert( "found it" );
} else {
    alert( "not found" );
}

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 ($).

answered Dec 14, 2010 at 21:45

fairfieldtfairfieldt

8411 gold badge6 silver badges10 bronze badges

0

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

16.6k3 gold badges25 silver badges44 bronze badges

answered Nov 9, 2015 at 9:43

1

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/

answered Nov 28, 2013 at 21:01

How do you check if a word contains a letter in javascript?

Oliver NiOliver Ni

2,5387 gold badges30 silver badges43 bronze badges

0

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

answered May 4, 2015 at 14:32

learner010learner010

3454 silver badges17 bronze badges

If you are reading data from the DOM such as a p or h2 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

Text you need to read one

Text you need to read two

Text you need to read three

JS

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

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

answered Feb 2, 2019 at 1:24

How do you check if a word contains a letter in javascript?

0

Working perfectly.This exmple will help alot.




    

My form

UserName :

Password :

How do you check if a word contains a letter in javascript?

chriz

1,3332 gold badges16 silver badges32 bronze badges

answered Aug 7, 2013 at 11:56

MankitaPMankitaP

571 gold badge1 silver badge7 bronze badges

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";
}

answered Feb 20 at 3:44

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

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

answered Jun 21, 2021 at 14:16

How do you check if a word contains a letter in javascript?

shasi kanthshasi kanth

6,86324 gold badges107 silver badges156 bronze badges

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.

answered Oct 12, 2019 at 22:30

How do you check if a word contains a letter in javascript?

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/

 


  
  attributeContains demo
  


 




 

 


answered Feb 12, 2021 at 1:51

How do you check if a word contains a letter in javascript?

1

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

answered Sep 2, 2021 at 21:04

How do you check if a word contains a letter in javascript?

Demonstration: The include() method finds the “contains” character in whole string, it will return a true.

var string = "This is a tutsmake.com and this tutorial contains javascript include() method examples."

str.includes("contains");

//The output of this

  true

answered Sep 2, 2019 at 10:48

How do you check if a word contains a letter in javascript?

DeveloperDeveloper

87010 silver badges6 bronze badges

How do you check if a string contains a letter in JavaScript?

To check if a string contains any letters, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!

How do you check if an element is a letter in JavaScript?

To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned.

How do you check if a string contains a certain letter?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you check if a string contains a specific word JS?

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.