Extracting from URL - Long URL - javascript

I'm currently trying to extract from ReturnUrl= ... I want to extract the URL from the link below using javascript. Can anyone help?
http://testdealbuilderCCMS/questionnaire.aspx?db_template_reference=Construction: Westfield Services Agreement&ContractDescription=Facilities Contract&NatureServices=FACILITIES&SiteDescription=Retail Units&ThirdPartyAgreementsList=&ServiceFee=1000&ReturnUrl=http://localhost:4965&launcher.aspx?directLink=PX&caseKey=7ccef65756504a79bc3a4a6687c0d9555e519ec9079241c9944c6a523704&PXid=

there are lots of edge cases here that will make this fail. So be careful, use this only if your string always ends with the ReturnURL parameter.
Find the position of the ReturnURL= in the string then get the substring from ReturnURL= position + ReturnURL= length, to the end.
http://jsfiddle.net/3hvajedg/1/
the_string = 'http://testdealbuilderCCMS/questionnaire.aspx?db_template_reference=Construction: Westfield Services Agreement&ContractDescription=Facilities Contract&NatureServices=FACILITIES&SiteDescription=Retail Units&ThirdPartyAgreementsList=&ServiceFee=1000&ReturnUrl=http://localhost:4965&launcher.aspx?directLink=PX&caseKey=7ccef65756504a79bc3a4a6687c0d9555e519ec9079241c9944c6a523704&PXid=';
alert(the_string.substring((the_string.indexOf('ReturnUrl=')+'ReturnUrl='.length)));

Related

read/get # value from url in PHP or Javascript

I'm currently developing a site in which a user can create a user area with a user directory created at registration such as myWebsite.com/user/myUserName
Now I've seen YouTube & TikTok (and presumably more) use an url like myWebsite.com/user/#myUserName (note the "#")
So my question is how do I read these? if a user visits myWebsite.com/user/#myUserName how do I read the # data?
I've searched many SO questions and Google before asking this and can't seen to find answers. only for standard url params or hashtags but not #, help!
Solution
You can use the window.location.pathname API to read the path name, parse it into an array and then filter out the only item that starts with an "#" character.
// take the entire path from the window and split them into an array with /
const paths = window.location.pathname.split('/')
// paths = ["","user","#myUserName"]
// pick out the first item in the array starting with an "#:
const userName = paths.find((item) => item.at(0) === "#")
// userName = "#myUserName"
Explanation
Firstly, you need to understand the structure of a URL https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL
Looking at your example, the user id should be part of the path. To get the entire path of /my-path/#user-id, you can use window.location.pathname (MDN reference).
From there on, you can parse the path to get the user id with JavaScript
Alternative Answer
Or you can just use Regex and capture anything that comes after "#"
const final = window.location.pathname.match("#.*").at(0)
// note: not a complete solution because it captures the other parts of the URL following the `/#username/` path

userscript to remove consistent string from URLs

I am trying to write a simple userscript for practice with this concept. Please forgive this example, but its the first one I can think of.
So on sports illistrated swimsuit images, they deliver a smaller than original image. Here is a sample URL: (might be nsfw if you consider bikinis nsfw)
https://www.si.com/.image/c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/MTY4MjU5NDM2MzkyMDMyMTI5/chrissy-teigen6jpg.webp
So in order to manipulate the URL to load the original size image, I need to remove this exact string from every image URL I load on this website:
"c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/"
Removing that string from the image URL serves the largest image. I am trying to write a userscript to automatically remove that, but I struggling with where to start. I have basics in JS down (I love writing bookmarklets) but am struggling to write a userscript.
Thanks.
Check if the undesirable substring exists in the window.location.href, and if it does, .replace that part with the empty string.
// ==UserScript==
// #name Full SI images
// #include https://www.si.com/*
// #grant none
// ==/UserScript==
if (window.location.href.includes('c_limit')) {
window.location.href = window.location.href.replace('c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/', '');
}
To make it more dynamic in terms of coding, you might wanna try to enhance the possibility of passing a not-a-hard-code fixed substring that you would want to remove from the url ("c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/") since this might vary from photo to photo, right?. what if we could remove this substring regardless its string content?
The common substring part is c_limit hence we could use this as our starting point to get the rest of the substring after this(including this part) until we find the dimension digits just before the first forward slash after this whole substring on this URL. Check this example out, pal. Hope it helps understand this concept better! Cheers!
let urlStr = "https://swimsuit.si.com/.image/c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_700/MTg5NTA4MDYzMTE0MzA2ODIy/kim_si_domrep_jan2022_s9_01237_updated2_wmweb.webp";
const highResUrlStr = urlStr.replace(/c_limit.*\d[/]/g, "");
console.log(highResUrlStr);

JQuery String Concatenation within a String

I'd like to preface this by saying I'm new to JQuery and this may be a simple question, but I was unable to find a solution after searching to the best of my ability.
I am trying to build a path to an image, where I am working with an API which returns an object that gives part of the path but not the base path.
Ex:
Base path = Youtube.com/watch/?
Path piece from API: /gdsrhab
On line 29 you can see I am trying to perform string concatenation within trying to build the "results" string. I understand why this is not working the way I've set it up, but am not sure how to syntactically perform this (if possible).
I've also tried to create two variables: baseURL and apiURL, concatenate them and save the result into completeURL then substitute it in, but it JQuery takes the string literal "completeURL" instead of substituting the value of the variable. Could someone point me in the right direction for how to get the full path within the tag? Thanks in advance for your help.
Picture of my JQuery code
In the following picture you can see the second half of the path is missing
The error message I receive
You are using ES6 string templates at start, so you only need to set your variable inside the ${}, you dont need to concate it, the string template will do it for you. So instead of
<img src = 'http...../' + '${movie.poster_path}'}>
that will output something like:
<img src="'http://yoururl.com/'+'mypath'"
you only need to do
<img src = 'http://yoururl.com/${movie.poster_path}'>
inside your string template

What type of regexp would I need to extract image url from markdown?

Given the following
Some post content here
![Habits Are Hard to Build and Break](https://i.imgur.com/vv0UfA5l.png)
Yad ayaday dyaya
* Hi
* There
How could I extract the first image in markdown? E.g I basically want to parse it then save the first image to a variable like extractedImage "https://i.imgur.com/vv0UfA5l.png"
extractImageFromMarkdown(text) {
// somehow parse text to grab first image_url
return extractedImageUrl;
}
text.match(/!\[.*?\]\((.*?)\)/)[1]
This assumes that you can't have any escaped brackets though, like ![\]] which is probably a safe assumption. This will also get only the first image as requested.

JavaScript To Strip Page For URL

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.

Categories