2015-03-30 38 views
-2

我有一個聊天機器人回答問題,只有當我寫代碼的方式和代碼相同時:如果我寫了標籤「你好」,如果我在聊天機器人「你好」中說,它將不會回答。我必須用代碼中的大寫字母來寫它。有沒有一個函數可以忽略它並且即使我把它寫成「HeLlO」也可以回答它?有沒有一個函數會忽略JavaScript中的大寫字母?

if (message.indexOf("Bye")>=0 || message.indexOf("bye")>=0 || message.indexOf("Goodbye")>=0 || message.indexOf("Goodbye")>=0 ){ 
    send_message("You're welcome."); 
} 

回答

3

你可以在不區分大小寫模式使用正則表達式:

if (/bye/i.test(message)) { 
    send_message("You're welcome."); 
} 

而且,沒有必要來測試這兩個byegoodbye - 如果它包含goodbye那麼它顯然也包含bye

但是,如果你想測試不同的消息,正則表達式也使得這個簡單:

if (/bye|adios|arrivederci/i.test(message)) 
+0

是的,你說得對..thanks很多的幫助 – user2505070 2015-03-30 22:07:14

0

嘗試message.toLowerCase()爲大寫字母轉換爲小寫。

0

您可以嘗試使用toLowerCase方法來實現這一訣竅。

例子:

msg = "HeLlo" 
msg.toLowerCase() // "hello" 
msg.toLowerCase().indexOf("hello")>=0 // true 

或者你可以使用字符串原型,創造出不區分大小寫contains方法:

String.prototype.ci_contains = function(str){ 
    return this.toLowerCase().contains(str.toLowerCase()) 
} 

使用示例:

msg = "ByE" 
msg.ci_contains("bye") // True 
msg.ci_contains("Bye") // True 
+2

請以純文本發佈代碼,不是截圖。 – Barmar 2015-03-30 22:08:18

+0

好吧,這是完成:) – 2015-03-30 22:16:29

0

我sugest使用:

  • .toLowerCase()

這有助於康普艾不區分大小寫,即:

function compairWithNoCase(valueCompair1,valueCompair2) 
    { 
     return valueCompair1.toLowerCase().match(
             valueCompair2.toLowerCase() 
               )==valueCompair1.toLowerCase() 
    } 
/* 
compairWithNoCase('hElLo','HeLlO'); 
true 
compairWithNoCase('BYE','HELLO'); 
false 
compairWithNoCase('ByE','bYe'); 
true 
*/ 
相關問題