javascript for splitting url and removing last part - javascript

http://www.google.com/site!#656126.72367
In this url, how to split and remove the part from exclamatory mark when page loaded using JS.
I just want http://www.google.com/site

Use string replace method , match every character after ! with regular expression and replace with ""
var url = 'http://www.google.com/site!#656126.72367';
url = url.replace(/!.*/,"");

You could use:
var host = window.location.hostname; // will be www.google.com
var path = window.location.pathname; // will be /site
In the end, you will have:
var url = "http://" + host + path;
Note: you can also use window.location.protocol, which in this case is http::
var url = window.location.protocol + '//' + host + path;
Update: as suggested by Rajesh, the window.location object also has access to the hash:
var hash = window.location.hash; // will be 656126.72367
It might be useful to do a console.log(window.location) and see what's in there!
This method works even if the hash contains several ! or #

var url = 'http://www.google.com/site!#656126.72367';
url = url.substring(0, url.indexOf('!'));
document.write(url);
substring extracts the characters from a string, between two specified indices (in this case on the first occurence and then on !), and returns the new sub string.
jsFiddle demo

var url = "http://www.google.com/site!#656126.72367";
url = url.split('!')[0];
console.log(url);

Related

Remove trailing '/' from the end of URL

So I have the following bit of code which works to some extent.
var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var sanitized = url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
url = 'https://' + sanitized;
window.onload = function urlChange(){
location.replace(url);
}
The only issue is that once the url gets changed the page keeps reloading as if I have an infinite loop going on.
Any ideas?
Thanks!
You need to check if the url is actually changed, and only replace their location if it has been changed. You should also probably use window.url rather than manually constructing it from the protocol, host and pathname.
var sanitized = window.url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
sanitized = 'https://' + sanitized; // add https to the front
window.onload = function urlChange() {
if (window.url !== sanitized) {
location.replace(sanitized);
}
}
To update the url without actually updating the location (which results in reloading the browser), you may use the html5 pushState event:
var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var sanitized = url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
url = 'https://' + sanitized;
window.onload = function urlChange(){
window.history.pushState("object or string", "Title", url);
}
You could remove the "/" from the url only if exist at the end using endsWith() in the string.
You could check if the "/" exist at the end of hash or pathname and remove it
then redirect to wanted page without the "/" at end.
Also you need to skip homepage as it will always be "/" on the pathname
var url_view = window.location.href;
var url_path = window.location.pathname;
var url_hash = window.location.hash;
if(url_path.endsWith("/") || url_hash.endsWith("/")) {
//Skip Home Page
if(url_path !== "/"){
url_view = url_view.slice(0,-1);
window.location.replace(url_view);
}
}

Display the last part of URL javascript?

I need to display the last part of a URL using javascript!
I am using this code but this will display the entire URL:
<script language="javascript">
document.writeln(document.location);
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
</script>
if the URL look like this:
domain.com/something/file
i need to only display the "file".
The reason document.write(window.location) writes the location is because of the toString method of window.location, which really returns window.location.href.
// This will fallback to the location.pathname if this
// is not the location already or not an anchor.
var path = this.pathname || window.location.pathname;
var part = path.split('/').pop();
Pathname is everything after the domain name. So, http://example.com/something/file breaks down like this:
protocol: http:
hostname: example.com
pathname: something/file
href: http://example.com/something/file
(there is also port, search (?this=that) and hash (#hash), which would both be empty in this case)
So, I'm taking something/file and splitting it into an array wherever this is a /, which would be ["something", "file"]
After that I'm popping off the last part of the array, in this case "file"
Both window.location and any <a> tag have these properties. So, if you need to parse a URL, you can do the following in javascript:
var anchor = document.createElement('a');
anchor.href = '/about'; // this could be any relative or absolute url
And now anchor will have the all those properties if you need them. No need for a regex or anything.
UPDATE
In newer browsers (excluding IE unless you use url-polyfill), you can use URL instead of an <a /> like so:
const url = new URL('/about', this.location)
// or if you don't care about the host, you can do the following
// const url = new URL('http://localhost/about')
This contains all the other information, plus url.searchParams, which makes it so you don't have to parse the search string yourself either.
<script type="text/javascript">
var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); // alerts segment4
</script>
JsFiddle: http://jsfiddle.net/HNMV3/1/
var pathname = window.location.pathname,
part = pathname.substr(pathname.lastIndexOf('/') + 1);
replace(/-/g," ") and split(".html") will remove "hyphens" and ".html" from url,thus only keeping the path name only
var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])

Get URL Path without last segment

How can I get the URL Path of the current site, but without the last segment:
http://www.domain.com/first/second/last
I only need http://www.domain.com/first/second … with jQuery (or only JavaScript)
Using pop and URL api
this assumes the URL is not likely to change
I use document.URL since that is what is recommended
const url = new URL("https://www.example.com/first/second/last"); // new URL(document.URL)
let path = url.pathname.split("/");
path.pop(); // remove the last
url.pathname = path.join("/")
console.log(url)
Older answers: As requested by OP - with changes from comment
const url = "http://www.example.com/first/second/last", // document.URL,
shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)
Here is an alternative
const url = new URL("http://www.example.com/first/second/last"),
shortUrl = `${url.protocol}//${url.hostname}${url.pathname.slice(0,url.pathname.lastIndexOf("/"))}`
console.log(shortUrl)
http://jsfiddle.net/KZsEW
Try the following for all browsers:
var url = "http://www.domain.com/first/second/last"; // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))
alert(subUrl);
​
The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.
Note: The string is searched from the end to the beginning, but
returns the index starting at the beginning, at postion 0.
This method returns -1 if the value to search for never occurs.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf
Try this:
var url = 'http://www.domain.com/first/second/last';
for(var i=url.length-1; i>=0;i--){
if(url[i]!='/'){
url= url.substr(0,i);
}
else{
alert(url);
break;
}
}
I'm not sure this is the most elegant of solutions, but you just want the substring up to the last slash, or second to last if the last character is a slash. Here I first take the part of the URL that appears after the protocol (http:// or https://) so that on for example http://stackoverflow.com it returns http://stackoverflow.com.
var url = document.URL.split('://');
var last_slash;
var result;
if (url[1].charAt(url[1].length - 1) === '/') {
url[1] = url[1].substring(0, url[1].length - 1);
}
last_slash = url[1].lastIndexOf('/');
result = url[0] + '://' + ((last_slash !== -1) ? url[1].substring(0, last_slash) : url[1]);
edit: jsfiddle http://jsfiddle.net/CV6d4/

Get absolute path in javascript

Can you get the absolute path in html.
If i use location.href i can get the url but how can i trim the filename.html ?
IS there a better way to get the path.
Thanks!
location.pathname gives you the local part of the url.
var filename = location.pathname.match(/[^\/]+$/)[0]
The above gives you only the very last part. For example, if you are on http://somedomain/somefolder/filename.html, it will give you filename.html
For this page if you inspect the window.location object you will see
hash:
host: stackoverflow.com
hostname: stackoverflow.com
href: http://stackoverflow.com/questions/8401879/get-absolute-path-in-javascript
pathname: /questions/8401879/get-absolute-path-in-javascript
port:
protocol: http:
search:
Documentation at MDN
So location.pathname is what you want. And if you want to extract the last part use regex.
var lastpart = window.location.pathname.match(/[^\/]+$/)[0];
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
Or if you need everything from protocol to last '/' you can use:
new RegExp('[^?]+/').exec(location.href)
and don't worry that it will match to the first '/' because '+' is a greedy quantifier, which means it will match as much as it can. First part '[^?]' is to stop matching before parameters because '/' can appear in parameter values like t.php?param1=val1/val2.
Try this:
var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);
// "http://localhost:8080/public/help/index.html"
const loc = window.location.href;
// "http://localhost:8080/public/help/"
const path = loc.substr(0, loc.lastIndexOf('/') + 1);

Javascript remove characters utill 3 slash /

Whats the best to way, based on the input below, to get everything in the url after the domain:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var url = "http://www.domain.com.uk/asdsadsad/asdasdasda/#45435";
var url = "http://www.domain.com.uk/asdasdasda/?324324";
var url = "http://www.domain.com.uk/asdasdasda/";
The output:
url = "/sadsad/asdsadsad/asdasdasda/?asda=ggy";
url = "/asdsadsad/asdasdasda/#45435";
url = "/asdasdasda/?324324";
UPDATE: the domain its not always the same. (sorry)
Thx
You should really parse the URI.
http://stevenlevithan.com/demo/parseuri/js/
Every absolute URL consists of a protocol, separated by two slashes, followed by a host, followed by a pathname. An implementation can look like:
// Search for the index of the first //, then search the next slash after it
var slashOffset = url.indexOf("/", url.indexOf("//") + 2);
url = url.substr(slashOffset);
If the domain is always the same, a simple replace will work fine:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace("^http://www.domain.com.uk/", "");
You could also use RegEx:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace(/^[^\/]*(?:\/[^\/]*){2}/, "");
Assuming this is in the browser, creating an anchor element will do a lot of magic on your behalf:
var a=document.createElement('a');
a.href="http://somedomain/iouhowe/ewouho/wiouhfe?jjj";
alert(a.pathname + a.search + a.hash); // /iouhowe/ewouho/wiouhfe?jjj

Categories

Resources