http://example.com我想在浏览器窗口中测试 URL中的空搜索字符串,即 ie http://example.com/search/?s=,但不匹配/search/?s=withsearchterms在 后有任何搜索词的任何内容/search/?s=,然后使用if语句并.addClass显示一个 div 来警告没有输入搜索词。
我正在尝试使用 Javascript,g.test如下所示;RegEx根据几位 RegEx 测试人员的说法,该模式是有效的。但没有运气:
var href = window.location.href;
var contains = /[\/?s=]+/g.test(href);
if (contains) {
$("#no-search-terms").addClass("display-block");
}
我的正则表达式错误吗?难道是我的使用方式test不对?
编辑 11/29/2020
这项工作,感谢Heo:
var search = window.location.href;
var regex = /(?<=\/\?s=).*$/
var result=regex.exec( search )
if (result && result[0]=='') {
alert("The search terms are empty.");
} else {
alert("The search terms are not empty or no matched.");
}
但miknik 的答案要简单得多,不需要正则表达式。适用于 Chrome 87、Firefox 83 和 Safari 14:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
alert("The search terms are empty.");
}
千巷猫影
米脂
哔哔one
侃侃无极
BIG阳
相关分类