为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕码人2483693 2023-07-20 16:40:43
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.");      }
查看完整描述

5 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

您可以测试字符串末尾是否包含/?s=:


var url1 = 'https://example.com/?s=';

var url2 = 'https://example.com/?s=withsearchterms';

var regex = /\/\?s=$/;

console.log(url1 + '  ==> ' + regex.test(url1));

console.log(url2 + '  ==> ' + regex.test(url2));


输出:


https://example.com/?s=  ==> true

https://example.com/?s=withsearchterms  ==> false

解释:

  • \/\?s=- 预计/?s=

  • $- 尾随$锚定正则表达式在末尾,例如前面的文本必须出现在末尾

  • 因此,如果 url 没有搜索词,则测试返回 true(您可以反转if测试)


查看完整回答
反对 回复 2023-07-20
?
米脂

TA贡献1836条经验 获得超3个赞

这里不需要正则表达式,这样的东西在现代浏览器中应该可以正常工作:


const queries = new URLSearchParams(window.location.search)

if (queries.has("s") && queries.get("s").length == 0){

  // do stuff

}


查看完整回答
反对 回复 2023-07-20
?
哔哔one

TA贡献1854条经验 获得超8个赞

如果你想使用 REGEX,你可以使用exec()而不是test()因为测试函数不适合这种情况。尝试这个:


//URL-input

var href1 = 'http://example.com/?s='

var href2 = 'http://example.com/?s=xx'

var href3 = 'http://example.com/'


function alertsSearchString( href ){

  var regex = /(?<=\/\?s=).*$/

  var Container= regex.exec( href )

  if ( Container!=null && Container[0]=='' )

      alert( 'The search string is an empty string!' )

  else if (Container!=null)

      alert( 'The search string: ' + Container[0] )

  else 

      alert( "The Container is "

              + Container 

              +", because input URL isn't matched the \nREGEX :   "

              + regex.toString() )

}


//alerts-output

alertsSearchString( href1 )

alertsSearchString( href2 )

alertsSearchString( href3 )

输出:

First Alert : The search string is an empty string!
SecondAlert : The search string: xx
Third Alert : The Container is null because input URL isn't matched the 
              REGEX : /(?<=\/\?s=).*$/

细节:

正则表达式:(?<=\/\?s=).*$

  • (?<=\/\?s=)使用lookbehind来检查并跳过/?s=

  • .*匹配 后的零到多个字符/?s=

  • $前面的文本必须出现在末尾。

请参阅正则表达式演示

下面的来源是从您的示例编辑 11/22/2020使用exec()

var search = 'http://example.com/search/?s='

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


}


查看完整回答
反对 回复 2023-07-20
?
侃侃无极

TA贡献2051条经验 获得超10个赞

另一种(大部分)避免正则表达式的替代方案:


function isEmptySearch(urlString) {

    const url = new URL(urlString);

    const urlParams = url.search.replace(/^\?/, '').split('&').reduce( (acc, cur) => {

        const param = cur.split('=');

        acc[param[0]] = param[1];

        return acc;

    }, {});

    return !urlParams.s;

}


const testUrls = [

    "http://example.com/search/",

    "http://example.com/search/?s=",

    "http://example.com/search/?s=&foo=bar&baz",

    "http://example.com/search/?s=hello&foo=bar&baz"

];

testUrls.forEach( url => console.log(`${url}: empty search = ${isEmptySearch(url)}`) );

我想我更喜欢 Peter Thoeny 之前提出的正则表达式选项,因为它不太冗长,但这个版本可能会引起兴趣。


查看完整回答
反对 回复 2023-07-20
?
BIG阳

TA贡献1859条经验 获得超6个赞

忘记正则表达式,nodejsURL是你的朋友。https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_new_url_input_base

对于旧版 Nodejs 版本,您可以使用url.parsequerystring.parse

const { URL } = require('url');

const url1 = new URL('https://example.com/?s=');

const url2 = new URL('https://example.com/?s=withsearchterms');


function hasEmptyQuery(u) {

  return [...u.searchParams]

    .some(([key, value]) => value.length === 0);

}


console.log(hasEmptyQuery(url1));

// true


console.log(hasEmptyQuery(url2));

// false


查看完整回答
反对 回复 2023-07-20
  • 5 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信