简体   繁体   中英

Javascript how to use .includes() when you can hav random capital letters in a string

I need to make a program that gets user input string. How to check if a spesific words with .includes() that can have capital leters?

Easiest way is to get rid of the capital letters

inputString.toLowerCase().includes(str)

Otherwise you would need an alternative solution such as a regular expression.

according to MDN String.includes() specifications

The includes() method is case sensitive. For example, the following expression returns false:

'Blue Whale'.includes('blue'); // returns false

so if you want to use String.includes() and you want to check for variable data you should use the solution of converting the string to lowercase before calling .includes() .

if what you mean by specific word is that it is always the same word you want to check for (or string, it could have spaces), you have the option of regular expression:

// using the i flag here you check for the word multycaseworld case insensitively
var reggex = /\bmultycaseworld\b/i   // adding \b to match word boundary (avoiding cat to match both cat and caterpillar)
var string = 'some string with MulTyCaseWorld'

var result = string.match(reggex)
//result will hold an array with the match so if result.length > 0 then you have a match

https://jsfiddle.net/0gc5rpdv/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM