gpt4 book ai didi

javascript - 如何返回完全不区分大小写的匹配项并评估为真/假

转载 作者:行者123 更新时间:2023-11-30 19:38:56 25 4
gpt4 key购买 nike

这是一个 JavaScript 问题...

我正在尝试返回完全不区分大小写的匹配项。例如,如果我在输入框中输入 "yo",我希望它返回 true,这在我当前的方法中是这样做的,但它也会返回 true 对于以 "yo" 结尾或开头的任何内容(即 your)。我仍然希望像 "Yo!""yo, what's up" 这样的情况返回 true

我已经尝试过 startsWith()endsWith(),但我不确定该去哪里...

<!DOCTYPE html>
<html>
<body>

<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {
var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /yo/i];
var b = document.getElementById("input1").value;
document.getElementById("demo").innerHTML = arr1.some(regexp => regexp.test(b));
}
</script>

</body>
</html>

我想获得单词的精确匹配,而不仅仅是一个字符串。

最佳答案

我相信你在使用 \b Word Boundaries ,但您对它们的使用不正确。如果你阅读文档,你需要用 \b 元字符包裹你想要匹配的 word,比如 \bhello\b。试试下一个例子:

function myFunction() {
var arr1 = [/\bhello\b/i, /\bhi\b/i, /\bhey\b/i, /\byo\b/i];
var b = document.getElementById("input1").value;
document.getElementById("demo").innerHTML = arr1.some(regexp => regexp.test(b));
}
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>

关于javascript - 如何返回完全不区分大小写的匹配项并评估为真/假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619594/

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