I want to test the URL in a browser window for an empty search string, i.e
/?s=
, but not match anything like /search/?s=withsearchterms
that has any search terms after the /search/?s=
, and then use an if
statement and .addClass
to display a div that warns that no search terms were entered.
I'm trying to use Javascript and g.test
like below; the RegEx
pattern is valid, according to several RegEx testers. But no luck:
var href = window.location.href;
var contains = /[\/?s=]+/g.test(href);
if (contains) {
$("#no-search-terms").addClass("display-block");
}
Is my RegEx wrong? Is my use of test
wrong?
Edit 11/29/2020
This work, thanks to 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.");
}
But miknik's answer is much simpler with no need for regex. Works on Chrome 87, Firefox 83 and Safari 14:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
alert("The search terms are empty.");
}
I want to test the URL http://example.
in a browser window for an empty search string, i.e http://example./search/?s=
, but not match anything like /search/?s=withsearchterms
that has any search terms after the /search/?s=
, and then use an if
statement and .addClass
to display a div that warns that no search terms were entered.
I'm trying to use Javascript and g.test
like below; the RegEx
pattern is valid, according to several RegEx testers. But no luck:
var href = window.location.href;
var contains = /[\/?s=]+/g.test(href);
if (contains) {
$("#no-search-terms").addClass("display-block");
}
Is my RegEx wrong? Is my use of test
wrong?
Edit 11/29/2020
This work, thanks to 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.");
}
But miknik's answer is much simpler with no need for regex. Works on Chrome 87, Firefox 83 and Safari 14:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
alert("The search terms are empty.");
}
Share
Improve this question
edited Nov 29, 2020 at 17:27
BlueDogRanch
asked Nov 10, 2020 at 0:16
BlueDogRanchBlueDogRanch
5371 gold badge18 silver badges50 bronze badges
3
-
[]
in regex means any of those characters, order agnostic. Maybe you mean\/\?s=(?!testme)
? or something like that? – ggorlen Commented Nov 10, 2020 at 0:25 -
Thanks; I just want to match the exact
/?s=
and ignore anything that has search terms, like/?s=searchterms
so I can display a div that warns that no search terms were entered. – BlueDogRanch Commented Nov 10, 2020 at 0:29 -
May the
exec()
is a good choice for this case. – Tuan Bao Commented Nov 25, 2020 at 15:08
5 Answers
Reset to default 9You can test if end of string contains /?s=
:
var url1 = 'https://example./?s=';
var url2 = 'https://example./?s=withsearchterms';
var regex = /\/\?s=$/;
console.log(url1 + ' ==> ' + regex.test(url1));
console.log(url2 + ' ==> ' + regex.test(url2));
Output:
https://example./?s= ==> true
https://example./?s=withsearchterms ==> false
Explanation:
\/\?s=
- expect/?s=
$
- trailing$
anchors the regex at the end, e.g. preceding text must occur at the end- thus, the test returns true if the url has no search term (you can reverse your
if
test)
No need for regex here, something like this should work fine in modern browsers:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
// do stuff
}
Another alternative that (mostly) avoids regular expressions:
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./search/",
"http://example./search/?s=",
"http://example./search/?s=&foo=bar&baz",
"http://example./search/?s=hello&foo=bar&baz"
];
testUrls.forEach( url => console.log(`${url}: empty search = ${isEmptySearch(url)}`) );
I think I prefer the regex option presented earlier by Peter Thoeny as it's less verbose, but this version might be of interest.
If You want to use REGEX, you could use exec()
instead of test()
because the test function isn't good at the case.
Try this:
//URL-input
var href1 = 'http://example./?s='
var href2 = 'http://example./?s=xx'
var href3 = 'http://example./'
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 )
Output:
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=).*$/
Detail:
Regex expression: (?<=\/\?s=).*$
(?<=\/\?s=)
use lookbehind to check and skip/?s=
..*
match zero to more characters after/?s=
.$
preceding text must occur at the end.
See regex-demo
The source below is an edited from your example Edit 11/22/2020 using exec()
var search = 'http://example./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.");
}
Forget regex, nodejs URL
is your friend. https://nodejs/dist/latest-v14.x/docs/api/url.html#url_new_url_input_base
for legacy nodejs versions you can use url.parse
and querystring.parse
const { URL } = require('url');
const url1 = new URL('https://example./?s=');
const url2 = new URL('https://example./?s=withsearchterms');
function hasEmptyQuery(u) {
return [...u.searchParams]
.some(([key, value]) => value.length === 0);
}
console.log(hasEmptyQuery(url1));
// true
console.log(hasEmptyQuery(url2));
// false