Checking for exact URL - javascript

I am having an issue checking for the URL in the pages on my site.
This is what I have.
Checking for the exact string works well:
var url = location.pathname;
if ("url:contains('texas-ignition-interlock')") {
$("body").addClass("texas-ppc-page");
}
But when I have page url with similar words, both classes were added to both pages.
var url = location.pathname;
if ("url:contains('texas-ignition-interlock-device')") {
$("body").addClass("texas-ppc-device-page");
}
I also tried indexOf, and is didn't work do to the pages with similar names.
This is what I tried, and this works for the first example. Second example will have the first class added too.
if (window.location.href.indexOf("texas-ignition-interlock") > -1) {
$("body").addClass("texas-ppc-page");
}
if (window.location.href.indexOf("texas-ignition-interlock-devices") > -1) {
$("body").addClass("texas-ppc-device-page");
}
Now, I can still use the indexOf version. I would simply target the stuff on one page using the class .texas-ppc-page, and on the second page I would target using both classes of .texas-ppc-page.texas-ppc-device-page.
Is there a better way of doing this with JS or jQuery?

You can use split("/") to split location.pathname into string arrays.
location.pathname will be similar to /questions/41968769/checking-for-exact-url so by splitting this string with "/" will result into
["", "questions", "41968769", "checking-for-exact-url"]
now you can perform indexOf("") and it will return non -1 value if string matched exactly, like in this case if i do indexOf("url") function will return -1, and if i do indexOf("checking-for-exact-url") it will return 3.

If you prefer to examine the strings similarly to how you were, you can leverage a regex, via .test as seen below with the placeholders ^ and $, for start and end, respectively. Otherwise, indexOf will match even a portion of the string. Check out the following...
var url = 'texas-ignition-interlock-devices';
console.log(/^texas-ignition-interlock$/.test(url)); // false
console.log(/^texas-ignition-interlock-devices$/.test(url)); // true

Related

Checking for a specific URL regex

I need to check for a specific URL pattern using regex and not sure what would be the approach but I think it should not be too complex for this case and therefore regex would be the preferred solution. I just need to check that the exact strings #, shares and assets are in the appropriate slots, for example:
http://some-domain.com/#/shares/a454-rte3-445f-4543/assets
Everything in the URL can be variable (protocol, domain, port, share id) except the exact strings I'm looking for and the slots (slash positions) at which they appear.
Thanks for your help!
You can use
/^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i
let url = `http://some-domain.com/#/shares/a454-rte3-445f-4543/assets`
let matched = /^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i.test(url)
console.log(matched)
Decided to avoid regex and do it this way instead.
const urlParts = window.location.href.split('/');
if (urlParts[3] === '#' && urlParts[4] === 'shares' && urlParts[6] === 'assets') {
// code goes here...
}

Updating a URL by adding a value of 1

So let's say the URL I have is
"mywebsite.com/file/100/"
What I want is for it to be updated to
"mywebsite.com/file/101/"
"mywebsite.com/file/102/"
(and so on...)
when the keyword cannot be found.
init();
function init()
{
searchWord("key word");
}
function searchWord(word)
{
var pageResults = document.body.innerHTML.match(word);
if(pageResults)
{
alert("word found");
} else {
}
}
Right now my script searches for a key term, and what I need is for the page to be updated by a value of 1 (100 to 101 to 102 etc) when the keyword cannot be found.
I am a noob a Javascript, none of this code is mine. I just need help developing it. I have searched around for a while, but I can't find much.
Thanks.
Not sure if this gets points for elegance.
Split the url into segments
Dispose of empty segment caused by trailing "/" if present.
If the last segment is numeric, replace it with its numeric value + 1.
Join the segments back into a string.
(If you want the trailing slash you can re-add it.)
Code
var url = "mywebsite.com/file/100/"
var segments = url.split("/");
while(segments[segments.length-1]==""){
segments.pop();
}
var lastSegment = segments[segments.length-1];
if(!isNaN(lastSegment)){
segments[segments.length-1] = (parseInt(lastSegment)+1).toString();
}
updatedUrl = segments.join("/");
One liner just for fun.
var url = window.location.hostname + window.location.pathname.split('/').map(function(sgmt){return (sgmt != '' && !isNaN(sgmt)) ? parseInt(sgmt)+1 : sgmt}).join('/');
You may want to omit the window.location.hostname to use relative url paths instead. The next piece first splits the url at the / and then uses the .map() method on the new array. The function that gets passed looks for non-blank and numerical sections of the url. If it finds it, it adds 1. When finished, it makes the array a string again (with the new number in the url) using the .join() method.

If path contains directory

I want to trigger a digital marketing tag on every page which falls under a particular URL path, say example.com/sachin under the sachin directory.
I've tried if (location.href === 'example.com/sachin.*/') but somehow the condition doesn't seem to work.
What will be the correct if condition for location.href if I want to cover all different resources with in the URL path say under sachin directory?
I presume you want to check if the URL contains example.com/sachin. It's highly rarely that any URL ever would contain 4 forward-slashes but what you would do is utilize indexOf.
if(location.href.indexOf("example.com/sachin/") != -1){
//Do something
}
This basically says, if "example.com/sachin/" is found somewhere in the given string(in location.href in this case) on an indexposition that is not -1(which means that it doesn't exist), then execute.
You need to use Regular Expressions to match needed resources.
Something like that:
if(location.href.match(/^http:\/\/example.com\/sachin\//)){
//your staff here
}
Another approach to check for a specific directory in a url.
function urlContains(url, value) {
return ~url.indexOf(value);
}
if (urlContains(location.href, "/sachin/")) {
// found
} else {
// not found
}
The indexOf method checks a string for the value that is passed and returns -1 if a result was not found.
Instead of checking for == -1 or != -1 you can use the Bitwise NOT operator ~ to convert -1 to 0, which is a falsy value, non-zero values are treated are truthy values in javascript.

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

Javascript & Split Arrays

What I want to accomplish is simple. I want a button's text to change depending on what page your on.
I start this by using the following:
var loc_array = document.location.href.split('/');
Now that I have the url and split it in an array I can grab certain directories depending on the position, like so:
if (loc_array[loc_array.length-1] == 'stations'){
var newT = document.createTextNode("Stations & Maps");
}
Now this works if the directory is /test/stations/, however if someone types /test/stations/index.html then it doesn't work. How can you test against this without throwing in another if statement or using a similar conditional.
Actually both your examples work the same. /stations/ and /stations/index.html both get split into two strings; /stations/ has an empty string at the end. So length-2 would have worked. Where it wouldn't work would be /stations, which is up a level. But that wouldn't normally be an issue because if stations is a static directory, the web server will redirect the browser to /stations/ with the slash.
That won't happen if you're doing the routing yourself. If you're doing routing, it's not a good idea to index from the end of the list of path parts, are there might be any old rubbish there being passed as path-parameters, eg. /stations/region1/stationname2. In this case you should be indexing from the start instead.
If the application can be mounted on a path other than a root you will need to tell JavaScript the path of that root, so it can work out how many slashes to skip. You'll probably also need to tell it for other purposes, for example if it creates any images on the fly it'll need to know the root to work out the directory to get images from.
var BASE= '/path-to/mysite';
var BASELEVEL= BASE.split('/').length;
...
var pagename= location.pathname.split('/')[BASELEVEL];
// '/path-to/mysite/stations/something' -> 'stations'
I'm using location.pathname to extract only the path part of the URL, rather than trying to pick apart href with string or regex methods, which would fail for query strings and fragment identifiers with / in them.
(See also protocol, host, port, search, hash for the other parts of the URL.)
I don't think string splitting is the best approach here. I would do it using RegEx.
var reStations = /\/stations(\/)?/i;
if (reStations.test(document.location.href))
//Do whatever
Not sure exactly what you're looking for, see if this fits:
var loc_array = document.location.href.split('/');
// this will loop through all parts
foreach (var i in loc_array) {
switch (loc_array[i]) {
case "stations":
// do something
break;
// other cases
}
}
// or if you want to check each specific element
switch (loc_array[0]) {
case "stations": // assuming /stations/[something/]
if (typeof loc_array[1] != 'undefined' && loc_array[1] == "something") {
// do things
}
break;
}
if( document.location.href.split( "station" ).length > 1 ){
//...
}
I think I see where you are going with this... As someone stated above using a RegExp (regular expression) could be helpful... but ONLY if you had more than a single type of page to filter out (html/js/php/...), but for what it looks like you want to do. Try something like this:
var loc_array = document.location.href.split('/');
var i = loc_array.length-1;
var button_label = "default";
while(i>1)
{
//checks to see if the current element at index [i] is html
if(loc_array[i].indexOf(".html")>-1)
{
if(i>0)
{
var button_label = loc_array[i-1];
break;
}
}
i--;
}
alert(button_label);
What it does is:
capture the current URL(URI)
split it into an array
starting from the END of the array and working BACKWARDS, look for the first element that contains the ".html" file identifier.
We now know that the element BEFORE our current element contains the label we want to add to our buttons...
You can then take the value and assign it wherever you need it.
If you run out of elements, it has a default value you can use.
Not sure if this helps.....
I have tested the above code and it worked.
if (loc_array[4]=='stations')
if the url was http://www.example.com/test/stations/index.html, the values in the array would be:
[0] = "http:"
[1] = ""
[2] = "www.example.com"
[3] = "test"
[4] = "stations"
[5] = "index.html"
For simplicity's sake, supposing that there is an array of keywords (such as "station") that identify the pages, use a map and try to match its keys with the href string using indexOf,
var href = document.location.href ;
var identifiers = {
"station": "Stations & Maps" , //!! map keys to result strings
/* ... */
} ;
identifier_loop: //!! label to identify the current loop
for(var n in identifiers) { //!! iterate map keys
if( href.indexOf(n) !== -1 ) { //!! true if the key n in identifiers is in the href string
var newT = document.createTextNode( identifiers[n] ) ; //!! create new text node with the mapped result string
break identifier_loop ; //!! end iteration to stop spending ressources on the loop
}
}
Your example will show an empty string, cause the last item is empty; so you can simply make:
if (loc_array[loc_array.length-2] == 'stations')
{
var newT = document.createTextNode("Stations & Maps");
}

Categories