JavaScript如何判断字符串包含列表元素并获取对应匹配值
报错原因
some() 方法仅返回布尔值用来判断是否存在匹配项,且回调函数内的 website 是局部作用域变量,仅在回调内部可访问,外部直接调用就会抛出ReferenceError。
解决方法
方案1:获取第一个匹配项(最符合你的需求)
用Array.find()方法,它会返回数组中第一个符合判断条件的元素,如果没有匹配项则返回undefined,既可以用来判断是否存在匹配,也能直接拿到匹配值:
const websites = [ 'google', 'youtube', 'twitter', ] const url = window.location.href // 示例值:www.google.com/soooomethingelse // 查找第一个匹配的站点 const matchedSite = websites.find(website => url.includes(website)) if (matchedSite) { console.log(matchedSite) // 匹配成功时输出对应的站点名,比如 google }
方案2:获取所有匹配项
如果存在多个符合条件的元素需要全部提取,可以用Array.filter()方法,返回所有符合条件的元素组成的数组:
// 返回所有匹配的站点数组,没有匹配项时返回空数组 const matchedSites = websites.filter(website => url.includes(website)) if (matchedSites.length) { console.log(matchedSites) }
附加优化:不区分大小写匹配
如果需要忽略大小写判断匹配,可以统一转小写后再对比:
const matchedSite = websites.find(website => url.toLowerCase().includes(website.toLowerCase()))
内容的提问来源于stack exchange,提问作者T-Dog
相关产品推荐
相关产品推荐

