我试图将一个字符串匹配到另一个字符串中,但我无法做到这一点:
我想根据我正在输入的另一个字符串来匹配一个字符串,但当我“询问”“Aston Martin”是否以“Aston”开头时,我得到“false”。
编辑:
请注意,过滤器是“as you type”,在本例中,“Aston”末尾有一个空格。
重要提示:
根据@mplungjan的回答,我遇到了另一个关于过滤字符串末尾的空格的问题。测试它,我得到 charCode 160,所以我使用的解决方案是将替换应用于两个字符串:
.replace(String.fromCharCode(160), ' ')
var value = $("#brand").text();
var brand = $("#filter").val();
alert(brand.substr(0, value.length).toUpperCase() == value.toUpperCase());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">
最佳答案
使用indexOf == 0将显示以品牌开头的字符串,包括值中的空格!
var brand = $("#brand").text();
var value = $("#filter").val();
console.log(">"+brand+"<",">"+value+"<",brand.toUpperCase().indexOf(value.toUpperCase())==0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">
启动键:
$("#filter").on("keyup", function() {
var brand = $("#brand").text();
brand = brand?brand.toUpperCase():"";
var value = $("#filter").val();
value = value?value.toUpperCase():"";
if (brand && value) {
console.log(brand, value,brand.indexOf(value) == 0); // same as regex /^word /
}
else {
console.log("Something is empty");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">
关于javascript - 无法用 jQuery 匹配带有空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676737/