contains方法在JavaScript中用於檢查一個字串是否包含另一個字串,並傳回一個布林值(true或false)。其語法為:string.contains(substring),其中string是目標字串,substring是要尋找的子字串。
在JavaScript中使用contains方法
##什麼是contains方法?
contains方法用於檢查一個字串是否包含另一個字串,並傳回一個布林值:true或false。語法
<code class="js">string.contains(substring)</code>其中:
是要檢查的目標字串。
是要尋找的子字串。
用法
contains方法的使用非常簡單:方法,將子字串作為參數傳遞。
範例:
<code class="js">// 检查字符串是否包含另一个字符串 const message = "Hello, world!"; const result = message.contains("world"); console.log(result); // 输出:true</code>
注意事項
或
undefined,contains方法將傳回
false。
替代方法
除了contains方法,還有其他方法可以檢查字串是否包含另一個字串::如果子字串存在,傳回子字串在目標字串中第一次出現的索引,否則傳回-1。
:類似於contains,但它接受一個可選的起始索引參數。
以上是js中contains用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!