Is there a way using HTML css and JavaScript that I can find the URL of a webpage after the first 10 characters. For example, if the URL is random.com/abc the program would only get the /abc part of the URl and log it in the console. How can this be done?
Asked
Active
Viewed 60 times
1
-
`(new URL('http://www.example.com/abc/123')).pathname` – epascarello Oct 01 '21 at 17:38
-
Where is the URL? The webpage, a link, plain text? – epascarello Oct 01 '21 at 17:38
4 Answers
2
You need to get the pathname from the window location object.
window.location.pathname

Giusseppe
- 147
- 7
1
You can use window.location.href
along with substring()
to select a range of characters or characters after a particular index.
window.location.href.substring(10);

George Sun
- 968
- 8
- 21
1
To get the path, use the pathName.
console.log(window.location.pathname);
console.log((new URL('http://www.example.com/abc/123')).pathname);
There is no reason to split and use indexes.

epascarello
- 204,599
- 20
- 195
- 236
0
Yes, you can get this done, using window.location.href.
Example output:
window.location.href: 'https://stackoverflow.com/questions/69409934/javascript-get-portion-of-a-page-url'
You can split this string now, and get desired part:
window.location.href.split('/')
Output:
0: "https:"
1: ""
2: "stackoverflow.com"
3: "questions"
4: "69409934"
5: "javascript-get-portion-of-a-page-url"
length: 6
Now log this into console:
console.log(window.location.href.split('/')[3])
Your result:
'questions'

thismrojek
- 59
- 3