Extracting a specific part of a URL using regex in JavaScript - javascript

I'm fairly new to any kind of language but I need to modify a code at my work because the guy doing it previously left and no replacement.
I basically would like to put in a variable a specific part of a url.
The URLs look like this:
http://www.test.com/abc/hhhhhh/a458/example
I need to extract the a458 part and put it in a variable. This part is always at the same place but can be of variable length.
The URLs always have the same structure. I tried /hhhhhh\/{1}[a-z0-9]+\/{1}/g but it doesn't fully work. It keeps the hhh and the /.

no need for regex, just split it
var link = "http://www.test.com/abc/hhhhhh/a458/example";
var linkParts = link.split("/");
//If the link is always in that format then a458 or whatever
//would replace it will be in index 5
console.log(linkParts[5]);

Related

GTM - Truncated DataLayer Variable into Custom Javascript Variable

I currently have a dlv variable to store "First Name" (gtm.element.2.value) which is working correctly.
I also a dlv to store "D.O.B." which is also working correctly - gtm.element.5.value (this is formatted MM/DD/YYYY).
However, I'd like to only show the first initial in the First Name dlv and the Year in the DOB dlv. I'm thinking of utilizing a Custom JS variable but am open to ideas if there is an easier route.
Can anyone help provide what that Custom JS variable would look like? I've been searching for some examples but not having luck with this specific example.
Appreciate the help in advance!
To get the first initial (i.e. first character) of the First Name variable, you can indeed use a Custom JavaScript variable with this:
function() {
return {{first_name}}[0]; // Replace with the actual DLV reference
}
Similarly, to get just the year (YYYY) of the D.O.B., you can use a Custom JS variable:
function() {
return {{date_of_birth}}.split('/').pop(); // Replace with the actual DLV reference
}
Obviously you might want to add some checks to make sure the input is in a predictable format. For example, you might want to check that {{first_name}} is a string of non-zero length, and you might want to check that {{date_of_birth}} actually contains a date string with slash as the separator.

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Use an regular expression to grab part of a string in js/jquery

I have the following string :-
http://myapp.local/myapp/shop/products/admin/ShopProducts%5Bproduct_name%5D//ShopProducts%5BemailNotification%5D//ShopProducts%5Bemail_user%5D//ShopProducts%5Bactive%5D//ShopProducts%5Binstant_win%5D//ShopProducts%5Bmulti_buy%5D//ShopProducts%5Bprice%5D//ShopProducts%5Bquantity%5D//ShopProducts_page/2/ajax/shopproducts-grid
I only want to grab the last section as so on.. not this is a part of pager (needs some weird custom hack) and the page number in this case is 2 but could 2,3,4, 500...
ShopProducts_page/2/ajax/shopproducts-grid
What is the easiest way to do this using vanilla js or jquery or a structured way to grab the parts into some of an array that I'll be able to manipulate?
If there will always be double forward-slashes // in the path, you can simply do this:
//Where string is already defined to be the path
var sections = string.split('//');
var lastSection = sections[sections.length-1];

What does this javascript regular expression code do in dealing with URLS?

I am looking at someone elses codebase and I as a javascript noob and doubly so a regular expression noob I can't figure out what the following lines do:
var url = sel.anchorNode.parentNode.href;
var match = self.location.href.replace(/\/$/i, '');
var replaced = url.replace(match,'');
I read it as:
set the var url to the href value of the parent node of the currently selected node
sets the var match to the browsers current URL with the trailing '/' removed (if it exists)
sets the var replaced to the string returned in 1. with the string returned in 2. removed from it
If I am reading it correctly I just can't figure out how it would ever do anything. There isn't any situation, I can think of, where the parent node of a currently selected node would have an href value pointing to the current URL.
So I think I am reading it incorrectly.
Because the href property of an anchor is a fully-resolved URL (even if the href attribute is relative), what that does is remove the current page's path and get you back to a relative URL. E.g., on the page:
http://example.com/foo/bar/
with a link like
...
...you get the href from the anchor which is:
http://example.com/foo/bar/nifty.html
...and then remove http://example.com/foo/bar from it, giving you:
/nifty.html
In this case, of course, that's probably not what you actually want. :-) I have to admit I fail to see how the code is useful, out of context, but then context is king sometimes...

How to get an Id out of a Url client side?

If I have a URl like "/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" what would be the best way to get the ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d" out of the URL client side?
I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks
$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...
Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL.
The alternative is to just split the string by / and get last element.
EDIT: The example on how to retrieve UUID from the URI:
var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';
var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];
url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0], as in the example).
Proof: http://jsfiddle.net/p6zud/2/
EDIT 2: Shortened the pattern used for matching (see revision history for comparison).
If the id is always going to be the last section of the URI, you could do something like
var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];
using split, convert the url to an array of parameters. Then last array item in your case would be your ID.
there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
The simpliest:
var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];
Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d;
Try this
alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);

Categories

Resources