簡體   English   中英

Javascript如何在字符串中具有隨機大寫字母時使用.includes()

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

我需要制作一個獲取用戶輸入字符串的程序。 如何檢查帶有.includes()的特殊單詞是否可以包含大寫字母?

最簡單的方法是擺脫大寫字母

inputString.toLowerCase().includes(str)

否則,您將需要其他解決方案,例如正則表達式。

根據MDN String.includes()規范

include()方法區分大小寫。 例如,以下表達式返回false:

'藍鯨'.includes('blue'); //返回false

因此,如果要使用String.includes()並要檢查變量數據,則應在調用.includes()之前使用將字符串轉換為小寫的解決方案。

如果特定單詞的含義是它始終與您要檢查的單詞相同(或字符串,它可以有空格),則可以選擇正則表達式:

// 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM