How to check if url contains a sub-string using jQuery or javascript?


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?


Asked by:- Sam
1
: 10407 At:- 11/13/2017 11:42:46 AM
javascript check if url contains string jquery check if url has parameters javascript







3 Answers
profileImage Answered by:- jaya

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 ");
}
2
At:- 11/14/2017 7:58:35 AM
thanks, i tired method first only and it is working as needed 0
By : Sam - at :- 11/16/2017 12:16:33 PM


profileImage Answered by:- bhanu

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
}
0
At:- 5/17/2021 2:54:56 PM


profileImage Answered by:- manish

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.

0
At:- 4/29/2022 2:22:58 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use