JavaScript – Check If URL Contains Query String | ByteNota

JavaScript – Check If URL Contains Query String

The post shows you an easy to check whether a URL contains query string or not with JavaScript.

To do this in JavaScript we can either check window.location.search property or use Regex to check the current URL. Let’s take a look into below source to see how it works.

This approach is we can check the result of window.locaiton.search property. The search property returns querystring a part of current URL. Here are two examples about it.

Assume that the current URL is:

https://bytenota.com/contact?name=David&age=20 

The result of search property is:

Assume that the current URL is:

The result of search property is an EMPTY string.

Here is code using the search property approach:

function detectQueryString() < var currentQueryString = window.location.search; if (currentQueryString) < return true; >else < return false; >> 

You can see live version of this approach here by clicking on the “Run Example” button.

     

Current URL:

Result:

function detectQueryString() < var currentQueryString = window.location.search; if (currentQueryString) < return true; >else < return false; >> document.getElementById('url').innerHTML = window.location.href; if (detectQueryString()) < document.getElementById('result').innerHTML = 'The current URL contains query string.'; >else

← Back to the post.

This first approach is not suitable if you want to check a given URL. To do this you can consider the below Regex approach.

2. Use Regex to check a given URL

This approach is we will use regex to check an URL. The first we will need to define a regex pattern for detecting querystring.

The above simple regex will check whether the URL contain ? character and querystring name/value pair. If yes, the URL definitely contains a query string and vice versa.

Here is code using regex approach:

function detectQueryString(url) < // regex pattern for detecting querystring var pattern = new RegExp(/\?.+=.*/g); return pattern.test(url); >

You can see live version of this approach here by clicking on the “Run Example” button.

     * Example 1: 

Current URL:

Result:

* Example 2:

URL:

Result:

function detectQueryString(url) < // regex pattern for detecting ? character var pattern = new RegExp(/\?.+=.*/g); return pattern.test(currentUrl); >// example 1 document.getElementById('url1').innerHTML = window.location.href; // get the current URL var currentUrl = window.location.href; if (detectQueryString(currentUrl)) < document.getElementById('result1').innerHTML = 'The current URL contains query string.'; >else < document.getElementById('result1').innerHTML = 'The current URL does not contain query string.'; >// example 2 document.getElementById('url2').innerHTML = window.location.href; // get the current URL var url2 = 'https://bytenota.com/contact?name=David&age=20'; if (detectQueryString(url2)) < document.getElementById('result2').innerHTML = 'The given URL contains query string.'; >else

Источник

Check if the URL Bar Contains a Specified or Given String in JavaScript and jQuery

www.encodedna.com

The URL bar or the Address bar of a web browser contains the address of a website. The URL also contains parameters or arguments, which we often define dynamically to communicate with elements or objects on a web page. Sometimes we need extract the data that we pass to the URL as parameters. Here I’ll show you how to check if the URL bar contains a given or specified string or text or value using JavaScript indexOf() method.

Check if a URL contains a given string or value using JavaScript

You will need this if you are working on a web site that depends on data extracted from the URL. You can extract or read URL parameters at the Server side in Asp.Net (such as using QueryString) and using JavaScript methods at the client side itself.

Whether you are using jQuery or JavaScript for your frontend, you can simply use the indexOf() method with the href property using windows.location object.

Syntax for indexOf()

The method indexOf() returns the position (a number) of the first occurrence of a given string. It will return -1 , if it finds nothing that matches the given string.

You can use the indexOf() method with href property of windows.location object. For example,

var t = window.location.href.indexOf('&book=');

If the method finds the string &book= in the URL, it will return the location (a number) and the location to the variable t .

Note: The character & indicates that I am passing an extra parameter to the URL.

I wish to check if the URL contains the parameter ?book= in jQuery. My script would be …

if (window.location.href.indexOf('?book=') > 0) < // . do something >

Here’s a complete Markup with the Script to check using jQuery .

Using JavaScript

If you are using JavaScript, you’ll simply call a function using the button’s click s event. For example

<input type="button" onclick="checkUrl()" value="Check URL" /> <script> function checkUrl() < if (window.location.href.indexOf('?book=') > 0) < console.log("The URL contains ?book"); >> </script>

The result will be the same as we saw using jQuery.

In my next post, I have shared an example explaining how to replace a given string with another string in the URL bar using JavaScript or jQuery.

Источник

Check if URL Contains a String With JavaScript

Check if URL Contains a String With JavaScript

  1. Use indexOf() to Check if URL Contains a String
  2. Check if URL Contains a String Using a Regular Expression
  3. Use toString().includes() to Check if URL Contains a String

This article will teach you to check if a URL contains a string. We’ll do the checking using String.prototype.indexOf() , Regular Expression, and String.prototype.includes() .

Use indexOf() to Check if URL Contains a String

When a URL contains a string, you can check for the string’s existence using the indexOf method from String.prototype.indexOf() . Therefore, the argument of indexOf should be your search string.

The indexOf method works by searching for the first occurrence of that string in the URL. Meanwhile, you’ll need to use indexOf on window.location.href because it contains the URL of the current web page.

In the code below, we’ve used indexOf on window.location.href to check if the URL contains the string ‘tutorial’ .

if (window.location.href.indexOf("tutorial") > -1)   alert("The web page contains the string 'tutorial'"); > 

Check if URL Contains a String Using a Regular Expression

You can utilize a Regular Expression pattern to search if the URL contains a string. Meanwhile, you’ll need the test() method from RegExp.prototype.test() .

Since you are looking for a string in the URL, the pattern to search for should be the string itself. In the code below, we’ve used the test() method to match the string ‘html’ on DelftStack’s website.

if (/html/.test(window.location.href))   alert("The web page contains the string 'html'"); > 

Use toString().includes() to Check if URL Contains a String

A combination of toString() and the includes() method can determine if a URL contains a string. The toString() returns a string version of an object.

So, we’ll need it because we’ll get the URL from window.location , which is an object. Since we already have a string version of window.location , we can use the includes() method to determine if it contains a string.

However, the includes() method performs a case-sensitive search, and the search for hello will not match Hello . In the next code block, we’ve used the includes method and toString to determine if the URL contains the string «google» .

if (window.location.toString().includes("google"))   alert("There is 'google' in the URL"); > 

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — JavaScript String

Copyright © 2023. All right reserved

Источник

If URL contains this string then hide all divs with this class/id (loop script)

I am trying to hide some divs when url contains an specific string. For example, i have this code that hides the first div:

 
Hello
world
.
if (/info|mapo/.test(window.location.href))
  1. The first problem with the script is that it only hides the first div saying Hello, but i want to hide all the divs. So, i think it’s necessary to do a loop. ¿how can i do that?
  2. The second thing is running two different scripts to hide different divs according the url string content.

Maybe this can be achived by making an else function. Always the loop its necessary and even better if it’s executed after load page.

 
Hello
Hello2
world
.
if (/info|mapo/.test(window.location.href)) if (/all/.test(window.location.href))

The code will be execute in Database Activity of Moodle.

try using classes instead of ids

and then use document.getElementsByClassName to iterate over all selected elements. An ID must be assigned to only one element.

3 Answers 3

This script will help you.

       

Remeber that the ID is associated with just one element, so it won’t work if you’re trying to access more than one element.

@Gonzalo If you liked my solution, I invite you to give a positive vote to my answer or set it to your answer, to help me to be active on StackOverflow. Thanks!

I think i cannot: «Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score»

You’ve got a few issues here:

First, like user adeneo mentioned in their comment, you cannot share IDs. Classes, however, can be shared so you probably want your elements to say class=»ficha» .

Second, you want to hide or show divs based off of a string in the URL, but your URLs are composed of unique paths. You’re trying to hide divs, when you should just be building the pages differently. Unless there’s more information you need to add about this.

www.example.com/mapo is, at least in the representation you’ve provided, a different HTML page from www.example.com/info so why not build them as separate pages rather than going through unnecessary logic to show and hide elements?

The third issue: you don’t want a for loop so much as a for-each loop. This first question will give you direction on how to select all elements with the specified class:
JavaScript get elements by class name and tag name
Then using the array you’ve selected from the above information, you can use Javascript Documentation for using forEach on arrays to change your elements’ visibility.

Источник

Check if URL has certain string with PHP

I would like to know if some word is present in the URL. For example, if word car is in the URL, like www.domain.com/car/ or www.domain.com/car/audi/ it would echo ‘car is exist’ and if there’s nothing it would echo ‘no cars’.

This also depends if you just looking for the word car or if you also want the type of car or cars too. You might need preg_match, strpos, explode and in_array/array_search, really just depends. if you want something simple, just use strpos as suggested

What if the url contains the word «scared»? Should that print «car is exist»? If not, most of the answers here are wrong.

12 Answers 12

Try something like this. The first row builds your URL and the rest check if it contains the word «car».

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if (strpos($url,'car') !== false) < echo 'Car exists.'; >else

This is a good solution but just be wary that this will match a URL that has car anywhere. For example www.domain.com/car-pricing or www.domain.com/carparks will validate and output Car exists . Maybe it doesn’t matter in your case but for others it might be relevant!

$url = ‘http://’ . $_SERVER[‘SERVER_NAME’] . $_SERVER[‘REQUEST_URI’]; echo count(strpos($url,’category’)); gives me 1 regardless of whether category exist in the Url or not. Any idea why?

From PHP 8.0 onwards, you can also use str_contains($url, ‘car’) : php.net/manual/en/function.str-contains.php

I think the easiest way is:

if (strpos($_SERVER['REQUEST_URI'], "car") !== false) < // car found >

Perfect. I needed to match example.com/events/pagename to find any urls with «events» in them and it works!

This does not test the full url; only the path. It will not test against the scheme, domain, port, query parameters, or fragment.

$url = " www.domain.com/car/audi/"; if (strpos($url, "car")!==false) < echo "Car here"; >else
if( strpos( $url, $word ) !== false ) < // Do something >
// Check if URL contains the word "car" or "CAR" if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false) < echo "Car here"; >else
If you want to use HTML in the echo, be sure to use ' ' instead of " ". I use this code to show an alert on my webpage https://geaskb.nl/ where the URL contains the word "Omnik" but hide the alert on pages that do not contain the word "Omnik" in the URL.

Источник

Читайте также:  Write files with php
Оцените статью