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?
CodePudding user response:
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);
CodePudding user response:
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'
CodePudding user response:
You need to get the pathname from the window location object.
window.location.pathname
CodePudding user response:
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.