I want to test a URL for an empty search string, i.e /?s=
, but not match anything like /?s=withsearchterms
that has any search terms after the /?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 Javascipt 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/22/2020
Peter Thoeny's idea is close. But this throws the alert
"matches" all the time, for /?s=
and any search string, i.e. /?s=example
. Is the RegEx not correct?
var search = 'http://example.com/search/?s='
var regex = /\/\?s=$/;
if (regex.test(search)) {
alert("matches");
} else {
alert("no match");
}
from Using Javascript, .test and RegEx to evaluate a URL for /?s=
No comments:
Post a Comment