JavaScript To Strip Page For URL - javascript

We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!

I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));

You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.

What you can do is find the last index of "/" and then use the substring function.

Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.

How about this:
var page = location.split("/");
page.pop();
page = page.join("/");

I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.

Related

How to find a dynamic node class by pattern in JavaScript

I'm working on this WP plugin and I've been trying to get the ID of a custom post kinda thing that is declared in the body class on each page. So it goes like this;
<body class="(Bunch of other classes) ld-courses-1731-parent">
I'm trying to get the number 1731 in my JS function but the number is dynamic so I need to some regex matching with the string pattern.
Pattern: ld-courses-*INT VALUE*-parent
how can I do this with JS? Any help is much appreciated thank you so much.
You can use match if thats the only class in your body:
var classList = document.getElementsByTagName("body")[0].classList;
[...classList].forEach(function(thisClass) {
if (/ld-courses-\b/.test(thisClass)) {
var id = thisClass.match(/\d/g);
console.log(id.join(""));
}
});
<body class="another-class-before another-class-12-hasnum ld-courses-1731-parent another-class-12-hasnumaswell another-class-after">
</body>
Hi Laclogan in regards to your question yes it's possible for sure.
Correct me if i'm wrong but the number comes probably if it's changing for each post directly from the url.
The following site explains if this is the case how to get that number from the url.
https://www.sitepoint.com/get-url-parameters-with-javascript/
In addition you can use the function concat to combine the strings see this site for an example hope it helps.
https://www.w3schools.com/jsref/jsref_concat_string.asp
Could you confirm for me that the number is always present in the url or if this is not the case?

Getting query string from re written URL

I have url "SampleProject/profile/aA12". How can I get the value of the id from my rewritten URL using javascript? I want to get the "aA12" value.
Im using htaccess rewrite to rewrite my URL. Im new in rewritting url's. Any help will be appreciated. More powers and thank you.
You can use regex.
Try
'SampleProject/profile/aA12'.match(/\SampleProject\/profile\/(\w+)/)
'SampleProject/profile/aA12/xxx'.match(/\SampleProject\/profile\/(\w+)/)
'aA12' will be matched in both cases.
There are going to be quite a few ways to achieve your goal with JavaScript. A simple solution could be something like this:
let myURL = "SampleProject/profile/aA12";
let result = myURL.split('/').pop();
// returns "aA12"
The .split('/') method is dividing your string up into an array using the / character, and .pop() is simply returning the last element of that array.
Hope this helps! If you were looking for more advanced matching, i.e. if you wanted to ignore a potential query string on the end of the URL parameter, you could use regular expressions.
Their is a many way that you can use to achieve the desired method i made you a code pen in this link
var url = "SampleProject/profile/aA12";
let res = url.split('/').pop();
console.log(res)
https://codepen.io/anon/pen/KQxNja

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

Creating a Regular expression which matches python tuple structure

I'm doing a JavaScript plugin, launched at every page-load, that replaces every matching structure with a link... That link redirects to a web application/database. A resource for coders of the Mount&Blade game.
In theory is easy, but I've found an huge obstacle in my way to the success: Regular expressions.
Even helped by a program named QuickRegex I can't get the structure to match. Or if I don't do a proper conditioning it outputs wrong results. The matching structure is as follows:
(item_set_slot, "itm_heavy_crossbow", slot_item_multiplayer_item_class),
I want to pick item_set_slot and turn it into a link to http://mbcommands.ollclan.eu/#$1
This is the code I'm using, that works, more or less. ;)
/* Mount&Blade Command Database Linking by Swyter */
function swymbcommandshooker(){
/* Regular HTML Expressions */
document.getElementsByTagName("body")[0].innerHTML=document.getElementsByTagName("body")[0].innerHTML.replace(/[\(]([a-zA-Z_]+)[\,]/gi, "(<a href='http://mbcommands.ollclan.eu/#$1' title='[?] Take an look in the Command Database' target='_blank'>$1</a>,");
/* Python highlighter Support...*/
document.getElementsByTagName("body")[0].innerHTML=document.getElementsByTagName("body")[0].innerHTML.replace(/(</span>([_a-z]+)\,/gi, "(</span><a href='http://mbcommands.ollclan.eu/#$1' title='[?] Take an look in the Command Database' target='_blank'>$1</a>,");
}
addOnloadHook( swymbcommandshooker );
Thanks in advance.
Hm, I'm not sure if I have understand you correctly, but if you really just want the match "item_set_slot" in "(item_set_slot, "itm_heavy_crossbow", slot_item_multiplayer_item_class)," the following regex should do:
/^\(([a-z_]+),/i
The JavaScript to generate the URL could look like this:
var tuple = '(item_set_slot, "itm_heavy_crossbow", slot_item_multiplayer_item_class),';
var url = tuple.replace(/^\(([a-z_]+),.*/i, 'http://mbcommands.ollclan.eu/#$1');
Note the appended .* in the regex, which is needed to match the rest of the tuple.

Categories