Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何仅在regex以用户输入开始时匹配它?_Javascript_Html_Regex - Fatal编程技术网

Javascript 如何仅在regex以用户输入开始时匹配它?

Javascript 如何仅在regex以用户输入开始时匹配它?,javascript,html,regex,Javascript,Html,Regex,我正在做一个搜索栏,显示一个品牌是印度的还是外国的。结果是从JSON文件(使用fetch API)获取的。 这是代码片段- const matchList=document.querySelector(“#匹配列表”); //搜索data.json并对其进行过滤 const searchBrand=异步searchText=>{ const res=等待取数('https://api.jsonbin.io/b/5f3e87fd4d93991036190251'); const brands=a

我正在做一个搜索栏,显示一个品牌是印度的还是外国的。结果是从JSON文件(使用fetch API)获取的。 这是代码片段-

const matchList=document.querySelector(“#匹配列表”);
//搜索data.json并对其进行过滤
const searchBrand=异步searchText=>{
const res=等待取数('https://api.jsonbin.io/b/5f3e87fd4d93991036190251');
const brands=await res.json();
//获取与当前文本输入的匹配项
让匹配项=品牌。过滤器(品牌=>{
const regex=new RegExp(searchText,'gi');
返回brand.name.match(regex);
});
if(searchText.length==0){
匹配项=[];
matchList.innerHTML='';
}
outputHTML(匹配);
};
//显示HTML
const outputHTML=匹配项=>{
如果(匹配。长度>0){
常量html=匹配项
.map(匹配=>{
如果(match.country==='foreign'){
返回`
${match.name}(${match.country})
类别:${match.category}
`;
}否则{
返回`
${match.name}(${match.country})
类别:${match.category}
`;
}
})
.加入(“”);
matchList.innerHTML=html;
}
};
const search=document.querySelector(“#search”);
search.addEventListener('input',()=>{
搜索品牌(search.value);
});

哪个国家?
哪个国家?

在正则表达式中使用
^
匹配字符串开头


const regex=new RegExp('^'+searchText,'gi')

谢谢。这确实是个问题,但DOM绘画的主要问题是什么。当用户输入与任何品牌名称都不匹配时,我必须清除DOM,这是我忘记的。这就是为什么以前的结果仍然显示出来。再次感谢