Home > Mobile >  read/get @ value from url in PHP or Javascript
read/get @ value from url in PHP or Javascript

Time:01-12

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!

CodePudding user response:

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