return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('&')[0].substr(url.lastIndexOf("."));
I have above code which return [.exe] or [.pdf]
Where I expect only [EXE] or [PDF]
What changes do I require in the above code?
Just Add 1 to last Index
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('&')[0].substr(url.lastIndexOf(".") + 1);
Related
Time for me to ask some help as I simply do not understand the issue, spent a good 6 hours on this, going nowhere :-(
I have an Axios GET request which may have the last parameter empty.
axios.get(this.fetchAllUsersRoute + '/' + this.status + '/' + this.pagination + '/' + this.search);
My laravel route:
Route::get('/fetch-users/{status}/{pagination}/{search?}', 'MyController#fetchUsers')->name('fetch-users');
When the this.search is empty I am getting this:
Request URL: https://mywebsite.dev/fetch-users/0/1/
Request Method: GET
Status Code: 301 Moved Permanently (from disk cache)
It redirects to here on each request:
https://mywebsite.dev/fetch-users/0/1
The last / slash seems to be causing a redirection when this value is left empty.
As soon as I remove it, the problem stops...no redirection.
Any idea how I can make the last slash disappear if the last value is empty?
Thank you.
Your request is incompatible with the route. You can try to create request link like below.
var fetchAllUsersRoute = "https://mywebsite.dev"
var status = 'status'
var pagination = 'pagination'
var search
var url = fetchAllUsersRoute + '/' + status + '/' + pagination + (search != null ? ('/' + search) : '')
console.log(url)
// "https://mywebsite.dev/status/pagination"
search = 'search'
url = fetchAllUsersRoute + '/' + status + '/' + pagination + (search != null ? ('/' + search) : '')
console.log(url)
// "https://mywebsite.dev/status/pagination/search"
I am trying to extract the last part of a URL to track in GTM, but not include added parameters like "?gclid=...".
As in:
https://example.com/m/5f5a0a9472cf844b320b6136/?gclid=1234
I want to just extract the 5f5a0a9472cf844b320b6136.
So far I've used:
function() {
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
But that is giving me the gclid number. This issue is, that parameter only exists on the landing page, not subsequent pages.
so if I were to use length - 2] that won't work once they leave the landing page. It would return the /m/.
How do I escape the "?" string on the landing page?
You can do something like this which will be easier
function (){
paths = window.location.pathname.split("/")
return paths[paths.length-1]
}
maybe this will help
const strs = [
"https://example.com/5f5a0a9472cf844b320b6136/?gclid=1234/",
"https://example.com/m/5f5a0a9472cf844b320b6136/?gclid=1234/",
"https://example.com/m/n/5f5a0a9472cf844b320b6136/",
"https://example.com/m/n/5f5a0a9472cf844b320b6136",
];
strs.forEach((str) => {
// ********************
if (str.includes("?")) {
const parts = str.split("/?")[0].split("/");
console.log(parts[parts.length - 1]);
} else {
const lastChar = str.charAt(str.length - 1);
str = lastChar === "/" ? str.substring(0, str.length - 1) : str;
const parts = str.split("/");
console.log(parts[parts.length - 1]);
}
// ********************
});
Since your using GTM, enable and use the built-in "page path" variable instead, which does not include parameters:
function() {
return {{Page Path}}.split("/").pop();
}
pop() return the last element from the array (it also removes it from the array, which in this case does not matter).
Okay, I found an alternative solution that I thought I'd share. Because that variable string always totals 24 characters, I created a function to look for it.
function getQuoteId() {
var segments = window.location.pathname.split('/');
for (var i = segments.length - 1; i >= 0; i--) {
if (segments[i] && segments[i].length === 24) {
return segments[i];
}
}
return null;
}
This mitigates the trailing "/" as well as the added parameters, and it returns the path I was looking to isolate.
I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;
I have been digging in some javascript api's lately and I found the following line:
get_url_info: function($db_link) {
var ldst_href;
if ($db_link.data('ldst-href')) {
ldst_href = $db_link.data('ldst-href');
}
else {
ldst_href = $db_link.attr('href');
}
var matchs = ldst_href.match(/^http:\/\/([^\.]+)\..*playguide\/db\/(.*?)\/?(#.+)?$/);
var subdomain = matchs[1];
var path = matchs[2];
if (!eorzeadb.dynamic_tooltip && eorzeadb.versions.data) {
url = eorzeadb.cdn_prefix + 'pc/tooltip/' + eorzeadb.versions.data +
'/' + subdomain + '/' + path + '.js';
}
else {
url = ldst_href + '/jsonp/';
}
return {
'url': url,
'data_key': subdomain + '/' + path
};
},
This result is supposed the return an array which I assume is contained in the link. I'm having a hard time decrypting the link tho.
Does anybody have any experience with these kinds of links or a way that I could start out?
http://regexr.com/
Here you can understand all the parts of the regex. Basically, is looking for a pattern like this:
http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)
The result will be an array with the original link, followed by the domain, the first optional argument, and the hashtag, something like this
["http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)", "(blablah)", "(OPTIONAL)(optional/)", "#(probably some id)"]
It will then use that information to build a different link
I am copying a function that will take a youtube/vimeo url and return what site the video came from (vimeo/yt) as well as the video id.
Here's what I have so far: http://jsfiddle.net/csjwf/181/
<strong>Result:</strong>
<div id="result"></div>
function parseVideoURL(url) {
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).+$/);
return {
provider : RegExp.$1,
id : RegExp.$1 == 'vimeo' ? RegExp.$2 : RegExp.$3
}
}
var result = document.getElementById("result");
var video = parseVideoURL("http://www.youtube.com/watch?v=PQLnmdOthmA&feature=feedrec_grec_index");
result.innerHTML = "Provider: " + video.provider + "<br>ID: " + video.id;
var video = parseVideoURL("http://vimeo.com/22080133");
result.innerHTML += "<br>--<br>Provider: " + video.provider + "<br>ID: " + video.id;
Output:
Result:
Provider: youtube
ID: PQLnmdOthmA
--
Provider: vimeo
ID: 2208013
However, notice how for vimeo vids, if the url ends in the ID, the last number is always cut off. If you add a slash to the end of the vimeo url the id is pulled fully.
The .+$ at the end is requiring at least one character after the last digit that is captured as a string of digits. That will chop one digit off what is captured. Is there a reason you have that there?
You can change the last + to a * like this:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).*$/
or even better, get rid of the end part entirely since it doesn't look like it's needed:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/
Here's a bit safer way to write your function that allows for any order of the query parameters in the youtube URL and doesn't put stuff into the regex that doesn't need to be there. The code is longer, but it's much more robust and would be much easier to add more providers:
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
if (url.indexOf("youtube.com/watch") != -1) {
retVal.provider = "youtube";
retVal.id = getParm(url, "v");
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
}
return(retVal);
}
Working version here: http://jsfiddle.net/jfriend00/N2hPj/
Here is an updated version that also works with youtu.be and youtube.com/embed urls using #jfriend00's code and some code found here: JavaScript REGEX: How do I get the YouTube video id from a URL?.
EDIT: Updated my answer (and the fiddle) with a function that actually works. :-)
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
var success = false;
if ( url.match('http(s)?://(www.)?youtube|youtu\.be') ) {
if (url.match('embed')) { retVal.id = url.split(/embed\//)[1].split('"')[0]; }
else { retVal.id = url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
retVal.provider = "youtube";
var videoUrl = 'https://www.youtube.com/embed/' + retVal.id + '?rel=0';
success = true;
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
var videoUrl = 'http://player.vimeo.com/video/' + retVal.id;
success = true;
}
if (success) {
return retVal;
}
else { alert("No valid media id detected"); }
}
And a working jsfiddle: http://jsfiddle.net/9n8Nn/3/
Out of the two stackexchange answers, this is the code that worked best for me in the end.
To simplify your regex I would use haystack.indexOf(needle) to determine if the url is vimeo or youtube and then apply site specific regex. Much easier, and later you can add video sites without overly complicating the regex.
Last number gets cut off because you're using ".+" at the end, which means "one or more of any character". Replace the + with a *, meaning "zero or more".
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+).+|(\d+))$/);
Remove the last . and the end matching
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/);