Skip to content
Advertisement

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!

Advertisement

Answer

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.

JavaScript

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 “@”

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement