How to check if the URL contains a given string?
JavascriptJqueryUrlJavascript Problem Overview
How could I do something like this:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
Javascript Solutions
Solution 1 - Javascript
You need add href property and check indexOf
instead of contains
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
}
});
</script>
Solution 2 - Javascript
if (window.location.href.indexOf("franky") != -1)
would do it. Alternatively, you could use a regexp:
if (/franky/.test(window.location.href))
Solution 3 - Javascript
You would use indexOf
like this:
if(window.location.href.indexOf("franky") != -1){....}
Also notice the addition of href
for the string otherwise you would do:
if(window.location.toString().indexOf("franky") != -1){....}
Solution 4 - Javascript
window.location
isn't a String, but it has a toString()
method. So you can do it like this:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
From the old Mozilla docs:
> Location objects have a toString > method returning the current URL. You > can also assign a string to > window.location. This means that you > can work with window.location as if it > were a string in most cases. > Sometimes, for example when you need > to call a String method on it, you > have to explicitly call toString.
Solution 5 - Javascript
like so:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("cart") > -1)
{
alert("your url contains the name franky");
}
});
</script>
Solution 6 - Javascript
The regex way:
var matches = !!location.href.match(/franky/); //a boolean value now
Or in a simple statement you could use:
if (location.href.match(/franky/)) {
I use this to test whether the website is running locally or on a server:
location.href.match(/(192.168|localhost).*:1337/)
This checks whether the href contains either 192.168
or localhost
AND is followed by :1337
.
As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.
Solution 7 - Javascript
document.URL
should get you the URL
and
if(document.URL.indexOf("searchtext") != -1) {
//found
} else {
//nope
}
Solution 8 - Javascript
Try this, it's shorter and works exactly as window.location.href
:
if (document.URL.indexOf("franky") > -1) { ... }
also if you want to check the previous URL:
if (document.referrer.indexOf("franky") > -1) { ... }
Solution 9 - Javascript
Easier it gets
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.href;
if(url.includes('franky')) //includes() method determines whether a string contains specified string.
{
alert("url contains franky");
}
});
</script>
Solution 10 - Javascript
It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.
This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:
var string= location.href;
var convertedString= string.toLowerCase();
if(convertedString.indexOf('franky') != -1)
{
alert("url has franky");
}
else
{
alert("url has no franky");
}
Solution 11 - Javascript
Try this:
<script type="text/javascript">
$(document).ready
(
function ()
{
var regExp = /franky/g;
var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
if(regExp.test(testString)) // This doesn't work, any suggestions.
{
alert("your url contains the name franky");
}
}
);
</script>
Solution 12 - Javascript
Try indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
You can also try search (for regular expressions)
if (foo.search("franky") >= 0)
{
...
}
Solution 13 - Javascript
> Use Window.location.href to take the url in javascript. it's a > property that will tell you the current URL location of the browser. > Setting the property to something different will redirect the page.
if (window.location.href.indexOf('franky') > -1) {
alert("your url contains the name franky");
}
Solution 14 - Javascript
I like to create a boolean
and then use that in a logical if
.
//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);
if (!onLoginPage) {
console.log('redirected to login page');
window.location = "/login";
} else {
console.log('already on the login page');
}
Solution 15 - Javascript
I like this approach, instead.
top.location.pathname.includes('franky')
It works in many cases.
Solution 16 - Javascript
Put in your js file
var url = window.location.href;
console.log(url);
console.log(~url.indexOf("#product-consulation"));
if (~url.indexOf("#product-consulation")) {
console.log('YES');
// $('html, body').animate({
// scrollTop: $('#header').offset().top - 80
// }, 1000);
} else {
console.log('NOPE');
}
Solution 17 - Javascript
Regular Expressions will be more optimal for a lot of people because of word boundaries \b
or similar devices. Word boundaries occur when any of 0-9
, a-z
, A-Z
, _
are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.
if (location.href.match(/(?:\b|_)franky(?:\b|_)))
If you use if(window.location.href.indexOf("sam")
, you'll get matches for flotsam
and same
, among other words. tom
would match tomato and tomorrow, without regex.
Making it case-sensitive is as simple as removing the i
.
Further, adding other filters is as easy as
if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))
Let's talk about (?:\b|_)
. RegEx typically defines _
as a word character
so it doesn't cause a word boundary. We use this (?:\b|_)
to deal with this. To see if it either finds \b
or _
on either side of the string.
Other languages may need to use something like
if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.
All of this is easier than saying
var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it
// more for other filters like frank and billy
Other languages' flavors of Regular Expressions support \p{L}
but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]
Solution 18 - Javascript
a window location is an object that contains multiple methods and props some of them is strings related to URL so you can search for the targeted string safely:
const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// another option
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true
Solution 19 - Javascript
Suppose you have this script
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow
The text written to <p id="response">
will be stack
Solution 20 - Javascript
This is my code ♥
function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
return true;
}
else {
console.log("Error", "The link is not valid");
}
return false;}
Solution 21 - Javascript
You can use javascript string method match
const url = window.location.href;
const find = 'questions';
const found = url.match(find);
console.log(url);
if(found !== null && found[0] === find){
console.log('You are in the questions page');
} else {
console.log('You are not in the questions page');
}