猿问

使用 Javascript、.test 和 RegEx 评估 URL 中的 /?s=

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.");

      

}


慕码人2483693
浏览 178回答 5
5回答

千巷猫影

您可以测试字符串末尾是否包含/?s=:var url1 = 'https://example.com/?s=';var url2 = 'https://example.com/?s=withsearchterms';var regex = /\/\?s=$/;console.log(url1 + '&nbsp; ==> ' + regex.test(url1));console.log(url2 + '&nbsp; ==> ' + regex.test(url2));输出:https://example.com/?s=&nbsp; ==> truehttps://example.com/?s=withsearchterms&nbsp; ==> false解释:\/\?s=- 预计/?s=$- 尾随$锚定正则表达式在末尾,例如前面的文本必须出现在末尾因此,如果 url 没有搜索词,则测试返回 true(您可以反转if测试)

米脂

这里不需要正则表达式,这样的东西在现代浏览器中应该可以正常工作:const queries = new URLSearchParams(window.location.search)if (queries.has("s") && queries.get("s").length == 0){&nbsp; // do stuff}

哔哔one

如果你想使用 REGEX,你可以使用exec()而不是test()因为测试函数不适合这种情况。尝试这个://URL-inputvar href1 = 'http://example.com/?s='var href2 = 'http://example.com/?s=xx'var href3 = 'http://example.com/'function alertsSearchString( href ){&nbsp; var regex = /(?<=\/\?s=).*$/&nbsp; var Container= regex.exec( href )&nbsp; if ( Container!=null && Container[0]=='' )&nbsp; &nbsp; &nbsp; alert( 'The search string is an empty string!' )&nbsp; else if (Container!=null)&nbsp; &nbsp; &nbsp; alert( 'The search string: ' + Container[0] )&nbsp; else&nbsp;&nbsp; &nbsp; &nbsp; alert( "The Container is "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + Container&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; +", because input URL isn't matched the \nREGEX :&nbsp; &nbsp;"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + regex.toString() )}//alerts-outputalertsSearchString( href1 )alertsSearchString( href2 )alertsSearchString( href3 )输出:First&nbsp;Alert&nbsp;:&nbsp;The&nbsp;search&nbsp;string&nbsp;is&nbsp;an&nbsp;empty&nbsp;string! SecondAlert&nbsp;:&nbsp;The&nbsp;search&nbsp;string:&nbsp;xx Third&nbsp;Alert&nbsp;:&nbsp;The&nbsp;Container&nbsp;is&nbsp;null&nbsp;because&nbsp;input&nbsp;URL&nbsp;isn't&nbsp;matched&nbsp;the&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;REGEX&nbsp;:&nbsp;/(?<=\/\?s=).*$/细节:正则表达式:(?<=\/\?s=).*$(?<=\/\?s=)使用lookbehind来检查并跳过/?s=。.*匹配 后的零到多个字符/?s=。$前面的文本必须出现在末尾。请参阅正则表达式演示下面的来源是从您的示例编辑 11/22/2020使用exec()var search = 'http://example.com/search/?s='var regex = /(?<=\/\?s=).*$/&nbsp; &nbsp;&nbsp;var result=regex.exec( search )if (result && result[0]=='') {&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; alert("The search terms are empty.");&nbsp; &nbsp; &nbsp;&nbsp;} else {&nbsp; alert("The search terms are not empty or no matched.");}

侃侃无极

另一种(大部分)避免正则表达式的替代方案:function isEmptySearch(urlString) {&nbsp; &nbsp; const url = new URL(urlString);&nbsp; &nbsp; const urlParams = url.search.replace(/^\?/, '').split('&').reduce( (acc, cur) => {&nbsp; &nbsp; &nbsp; &nbsp; const param = cur.split('=');&nbsp; &nbsp; &nbsp; &nbsp; acc[param[0]] = param[1];&nbsp; &nbsp; &nbsp; &nbsp; return acc;&nbsp; &nbsp; }, {});&nbsp; &nbsp; return !urlParams.s;}const testUrls = [&nbsp; &nbsp; "http://example.com/search/",&nbsp; &nbsp; "http://example.com/search/?s=",&nbsp; &nbsp; "http://example.com/search/?s=&foo=bar&baz",&nbsp; &nbsp; "http://example.com/search/?s=hello&foo=bar&baz"];testUrls.forEach( url => console.log(`${url}: empty search = ${isEmptySearch(url)}`) );我想我更喜欢 Peter Thoeny 之前提出的正则表达式选项,因为它不太冗长,但这个版本可能会引起兴趣。

BIG阳

忘记正则表达式,nodejsURL是你的朋友。https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_new_url_input_base对于旧版 Nodejs 版本,您可以使用url.parse和querystring.parseconst { URL } = require('url');const url1 = new URL('https://example.com/?s=');const url2 = new URL('https://example.com/?s=withsearchterms');function hasEmptyQuery(u) {&nbsp; return [...u.searchParams]&nbsp; &nbsp; .some(([key, value]) => value.length === 0);}console.log(hasEmptyQuery(url1));// trueconsole.log(hasEmptyQuery(url2));// false
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答