在搜索栏中使用 javascript 问题自动纠正大写字母

问题描述 投票:0回答:1

嘿,伙计们,我有一个搜索栏,我想让它在用户搜索时自动更正和搜索,

eg- 用户输入 jane doe,它将更正为 Jane Doe

这很痛苦,因为我无法添加名称的 2 个变体,因为它不起作用,所以基本上用户必须键入我的 javascript 中的确切格式,否则搜索将不会返回任何结果

任何帮助都会很棒

              <form action="" style="margin-bottom: 40px;">
                <div class="input-group">
                  <input type="search" id="search" autocomplete="off" onchange="openPage()"  class="form-control rounded-pill rounded-end-0 border-0 ps-4" placeholder="Search Celebrity Bones...">
                  <button type="button" id="button" onclick="openPage()" value="Chercher" class="btn btn-primary rounded-pill rounded-start-0 shadow-none">
                    <i class="fa fa-search"></i>
                  </button>
                </div>
              </form>     

这是我的 javascript,我知道它不是最好的,但我是使用搜索栏的新手,

function openPage() {
            var x = document.getElementById("search").value;

            if (x === "Jane Doe") { // if they don't search the exact name it won't work
               window.open ("files/Janedow.html"); // this is the file
            }
}

如果您查看我的 javascript,我尝试添加例如“Jane doe,Jane Doe”,但这行不通这将是完美的,因为我可以制作很多关键字

search input capitalize
1个回答
0
投票

您可以尝试使用正则表达式将每个单词的首字母替换为大写

var x = document.getElementById("search").value;
x = x.replace(/\b\w/g, (firstLetter) => firstLetter.toUpperCase());

if (x === "Jane Doe") { 
    window.open ("files/Janedow.html"); 
}

注意:这只是为了更正名称从

jane doe
Jane Doe


您还可以使用正则表达式来检查用户的输入是否包含

Jane Doe
(您可以为不区分大小写的正则表达式添加
i
标志)

const regex = /jane doe/i; 
if (regex.test(x)) { 
    window.open ("files/Janedow.html"); 
}
© www.soinside.com 2019 - 2024. All rights reserved.