How do i check if the current URL contains the sub-string using jQuery or javascript?
I need to select a anchor tag using class if a condition is met, suppose i need to check if URL has "/CRM" then select
if(URL.hasString('/CRM'))
{
$(".SelectURL").RemoveClass('Hide');
}
How to do it using jQuery or javascript?
You can check if a string contains substring in javascript by taking the URL using windows.location.href and then check the sub-string using .IndexOf("Substring") method , so your complete code will be as below
if (window.location.href.indexOf("/CRM") > -1) {
alert("Inside /CRM");
}
Or Second Method you can do it like below
if (location.href.match(/CRM/)) {
alert("in CRM ");
}
You can also try to use Regular expression in Javascript, then you can try below code to check if url contains a word or sub-string
if (/StringtoCheck/.test(window.location.href))
{
//yes it contains
}
regex may be helpful when the condition to check a given string in URL get's little bit tricky
OR
Simply use below code
if(window.location.href.indexOf("YourStringToCheck") != -1){
//string found code here
}
You can also use window.location
after converting it to string, something like below
if(window.location.toString().includes("test"))
{
//test exists
}
as Location
object have a toString
method returning the current URL.
OR
using document.URL
to check if string has substring using javascript.
if(document.URL.indexOf("searchtext") != -1) {
//found
} else {
//nope
}
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly