read/get # value from url in PHP or Javascript - 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

Related

window.location.href or window.location.search

I want to extract out the query string values from the URL.
So, in the most upvoted answer in How can I get query string values in JavaScript? - window.location.search is used.
Is there any problem in using window.location.href?
I am trying to root cause a problem where in sometimes I am getting empty query string value when using location.href
The 2 properties return different things:
href: Is a DOMString containing the whole URL.
and:
search: Is a DOMString containing a '?' followed by the parameters of
the URL. Also known as "querystring"
So you could use one or the other, just make sure to account for the differences between the returned values in your function. If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces.
Browsers now have a URLSearchParams class that can help to parse search params. It has been around in modern browsers for almost 4 years now: https://caniuse.com/?search=URLSearchParams
let queryParams = new URLSearchParams(window.location.search)
queryParams.set('page', '1')
queryParams.toString()
queryParams.get('page')
queryParams.delete('page')
i use
var qr={};
window.location.search.substring(1).split("&").forEach(p => { qr[p.split("=")[0]] = p.split("=")[1] })
//use
console.log(qr["sample"]);
//or
console.log(qr.sample);
Note - if there is not location.href.search value you will get a null string.
You can explore the DOM of a page - any page - using a browser's Inspect feature to look at values.
You can learn a lot about the DOM using this procedure - more than most every even hear about.
Open the inspector (how depends on the browser but try right clicking anywhere on the page and check the drop down menu that you'll see - it may read Inspect or Inspect Object.
Once the inspector is open, click on console in the menu at the top of the inspector frame.
For Foxfire, the input line, where you can type in things to explore the DOM is at the bottom of the inspector window and is prefixed with >>
Note - Chrome shows you a multi-line input field, Firefox only a one line field. If you have Chrome - use it to inspect things, after you type something and press Enter the value you want will be displayed under what you type and the cursor moved down to the next blank line so you can enter something else.
Firefox allows you to view things but it clunky and a tad harder to use.
Into the input line or field, type:
document.location.
A list of all the properties for the location of the document (the URL) will be displayed and it has auto fill in to help you.
For example:
document.location.search will show any text in the URL following the # sign in the URL
document.location.href will show the you the entire URL
document.location.host will show you the host part of the URL
Experiment and look at all the properties listed for document.location and you'll learn quite about bit about the document.location. property.
You can also type window. and see a list of the window object's property - one of which will be document.
Instead of typing document.location.href you could make it harder to type by typing window.document.location.href
They produce the same results because the top property is always assumed to be window.
For Firefox - After you type something and hit enter, the results will be displayed above the input line. To bring up what you last typed, so you can change it, press the up arrow key wile the cursor is in the input line.
With Chrome - as I said above, when you press enter, the value will be displayed the line you just typed and the cursor will be moved down to the next blank line where you can enter the name of another property to see what it's value is.
Explore top. and self. - you'll find the are the top window object (if there are multi-frames on the page - frames, not iframes) and the current window.
Spending some time exploring the properties of window. self. top. will teach you a lot about the DOM (Document Object Model) that you might not ever come across.
If you don't seen an input field or line, make sure you click Console in the inspector top menu.
If you decided to use, say, document.location.href you will code it like that in your JavaScript to get the value or to set the value - you can change the href and have the browser go to another web page.
Note - one of the other answers said
"If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces"
You need not split anything off. Explore all of the properties of document.location and you'll see that you can get the hash, search, etc. already "split off" from the location string.
Hash is the value after a pound sign (#) in the URL
Search is the value after a question mark (?) in the URL
Here are some other things to look at:
document.links
document.links[0]
document.URL
document.body
Just browse through the DOM - you will learn a lot.
Am assuming you know javascript array and few method
Use the window.location.href
var url = 'site.com/seach?a=val0&b=val1'
split the '?'
var someArray = url.split('?');
The someArray looks like this ['site.com/seach', 'a=1000&b=c']
index 0 is the window.location and index 1 is queryString
var queryString = someArray[1];
Go futher a split '&' so u get a key=value
var keyValue = queryString.split('&');
keyVal looks like this ['a=val0', 'b=val1'];
Now lets get keys and values.
var keyArray=[], valArray=[];
Loop through the keyValue array and split '=' the update keyArray and valArray
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
Finally we have
keyArray = ['a', 'b'];
valArray = ['val0', 'val1'];
Our full codes looks like this.
var url = 'site.com/seach?a=val0&b=val1';
var someArray = url.split('?');
var queryString = someArray[1];
var keyValue = queryString.split('&');
var keyArray=[], valArray=[];
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
DONE!

Passing variables to Javascript from "pretty" URL

My problem is, I would like to create "pretty" URLs for visitors that look like this:
http://domain.com/Name
I have users that often send friends to my service, and I have been created customized pages for each one with the person's First Name in the headline. E.g., "John, here's an easy way to fix this widget"
I then save the page as an index.html file in a custom folder so the link structure for the custom page is domain/Name with Name being their First Name.
This is getting tedious and I would love to use Javascript to automate the process. However, the only documentation I can find on passing variables to Javascript involves "ugly" domains such as domain/jspass2.html?FirstName=John&LastName=Smith
Is there a way to beautify these domains and still pass the variables to a javascript code that inputs their name into the html code? I don't want to "cloak" an ugly domain (using a href, for example)
Thanks for the help!
Well, you could make it "prettier" by making the querystring cleaner.
example:
http://www.domain.com/?John,Smith
The javascript in your index file can read that.
var getQueryString = function() {
queryString = window.location.search;
queryStringCleaned = queryString.substring(queryString.indexOf('?') + 1 );
return queryStringCleaned;
};
if "http://domain.com/Name" is your domain, variable firstName will have the value "Name".
var firstName = window.location.pathname.match(/([\w-]+)\/?.*/)[1];
You could just take the whole URL in JS, and parse it "by hand". Use this regex (for example) to find the parameters passed.
In addition to Paul, I wrote you something that extracts the first name field from the url you provided. If the format is consistent, and you can obtain the url in javascript, you can use this. You may possibly have to create the page first, then redirect the user because javascript is a client side language and the page will already be rendered.
var url = "domain/jspass2.html?FirstName=John&LastName=Smith";
url = url.slice(url.indexOf("FirstName=") + 10, url.length);
url = url.slice(0, url.indexOf("&"));

Extracting from URL - Long URL

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)));

How to get the domain name using regular expression in javascript?

I have just started to use regular expression and I am finding it difficult to find a regular expression to get the main domain name, that is, if I have urls as given below..
url = http://blog.example.co.in/page/category=?order.php
url = https://www.example.co.ca?page.html
so out of this I want to get only the example out the urls given above. So how can i do it..!!If you can get example in any other method will also be helpful..
I myself tried some methods as given below..
var url = urls.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/)[0];
var out = url.split('.')[0];
in this I am able to get the output for
https://www.example.co.ca?page.html
but not for
url = http://blog.example.co.in/page/category=?order.php
so can someone help me out a method that can get example out of any kind url
thank you

JS split OR Logical Operator

User inputs a web address that I want to get only the tail from, as I do know what site he inputs.
So first I want to remove the "main" URL and get what ever is at the end, so my action is:
Original link: http://example.com/something
var n=e.split("http://example.com/");e=n[1];
And I will get "something"
The problem is that site can also be secured, thus having https not http. Therefore the split wont work.
How do I define a split function, that would work like this:
split("http://example.com/ || https://example.com/")
I do not want to split by looking at "//" or anything of that sort, I want an exact address.
If you like it clear and want to avoid regular expressions, try this:
var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
If you wish to know the host you can do so by using this code instead in JavaScript:
window.location.host
Source Get The Current Domain Name With Javascript (Not the path, etc.)
You can also use window.location.path to get the URL that was requested, combining those you get:
window.location.host + window.location.pathname
For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.
var s = "http://example.com/something";
function split (url) {
var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
var a = r.exec(url)
return [a[1], a[2], a[3]];
}

Categories