gpt4 book ai didi

javascript - 如何使indexOf仅匹配 'hi'作为匹配而不匹配 'hirandomstuffhere'?

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:21 24 4
gpt4 key购买 nike

基本上,我前段时间一直在玩 Steam 机器人,当你在数组中说出内容时,它会自动回复,即“hello-triggers”数组,其中包含“hi”、“hello”等内容。我做到了,每当它收到一条消息时,它都会使用 indexOf() 检查匹配情况,一切正常,直到我注意到它会注意到“hiasodkaso”或“hidemyass”作为“hi”触发器。

因此它会匹配包含该单词的任何内容,即使它位于单词的中间。

我该如何让indexOf只注意到它是确切的单词,而不是同一个单词中的其他内容?

我没有我使用的脚本,但我会做一个非常相似的例子:

var hiTriggers = ['hi', 'hello', 'yo'];

// here goes the receiving message function and what not, then:

for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}

正则表达式不会用于此目的,对吗?因为它用于表达式或其他什么。 (我的英语不太好,ikr)

提前致谢。如果我对某些事情不够清楚,请告诉我,我会以另一种方式编辑/表述它! :)

最佳答案

您可以扩展原型(prototype):

String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

然后做:

var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);

或者,如果您不想扩展字符串对象:

foo.substr(i).search(/hi\b/); 

这两个示例均取自 Is there a version of JavaScript's String.indexOf() that allows for regular expressions? 的最佳答案

关于javascript - 如何使indexOf仅匹配 'hi'作为匹配而不匹配 'hirandomstuffhere'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com