简体   繁体   中英

Using .match() for case insensitive words

Currently I need to match the user input with an existing value and I have used,

 return book.id.match(keyword);

Now I need to make the keyword match to case insensitive where Bookt and BOOkT should also match for example. I tried using a regex but it is not letting me pass the 'keyword' variable to the regex. Any idea how to do this simply?

You can use match with regex as parameters.

var string = "BoOkt";
var result = string.match(/bookt/i);

if (result){
    alert('match');
}

alternate version from using regex is indexOf . If you have contain regex metacharacters from your user input and using match will be another problem for you.

var match = 'awesome';
var string = 'stackoverflow is AweSoMe place';

if (string.toLowerCase().indexOf(match) != -1){
    alert('match')
}

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