I'm checking with JS if the route I'm on includes a state or not, to activate a CSS class. These states are looped through, and I check with:
window.location.href.includes(url.contains)
This url.contains
can have different states (values), but I have two states which are: provisional-final-allegation
and final-allegation
.
Which are giving me problems because they are called almost the same, the difference is the provisional-
one that goes at the beginning. And includes()
he gives me both as valid, so they are activated at the same time.
Is there a way to make the method includes()
strict and check exactly what is passed to it as a parameter? or any other method that can help me?
The comment they left you with is fine too, but if the part you're looking for isn't at the beginning or end of the string it won't work with
endsWith
nistartsWith
.To do this, you'll need more than just
includes
, you can useRegExp
.You can use the following regular expression
What it does is basically find
provisional-final-allegation
andfinal-allegation
, the main part is to say that itprovicional-
's optional and if it's there then find it too, but if it's not there, just findfinal-allegation
.In this way, you can test it like this
As you can see, we use indexing brackets, since it
String.prototype.match
returns an array with the matches that the expression found, the output will be what it found.Working example:
The method
String.includes(substring)
tells you if one text is included in another. So my proposal is not to look inwindow.location.href
, but in another field ofwindow.location
:Let's imagine that the URL we have is
https://es.stackoverflow.com/questions/505444?pe=1&pa=hola#anchor
window.location.pathname
it is the part of the URL that comes just after the domain/IP address, indicating the path of the resource, but without parameters. In this case it would be:"/questions/505444"
window.location.search
is the part with the request params : what comes after the question mark, but not including the hash (#):?pe=1&pa=hola
window.location.hash
: As you can imagine, it is in this case#anchor
So you could, on the one hand, search only the part that interests you and, on the other hand,
.match(/^...$/)
) orsplit('/')
in the path (orsplit('&')
in the search part ) and look with `===' .I have solved it by making a
.split('/')
to the current URL, to obtain an array with each part of the string. Since the status came in the URL in this way:Now like this if you check the full state, whatever it is:
Thanks for the response, and the comments.