Display the last part of URL javascript? - 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])

Related

Convert any URL into a relative URL [duplicate]

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname.
The properties are the same as for the location object.
Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.
If by "relative URL" you mean the part of the string after the first single /, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single / in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp --> Out: /my/page.jsp
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
URL.getRelativeURL
There's an public-domain extension for the standard URL object called getRelativeURL.
It's got a few cool tweaks like force reload, you should check it out!
Try it live.       View on Gist.
Example usage
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";
don't forget that \ is an escape character in strings, so if you would like to write regex in strings, ensure you type \ twice for every \ you need. Example: /\w/ → "\\w"
Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
we want to url as below:
/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie,
var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
i think you guys got that point if you have still doubt let me know please
and to see changes in code by inspecting:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>

Replace the url parameter value using js

I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);

Check if URL has anything after second "/" using javascript / jquery

So I have a completely variable url:
www.whatever.com/something/pagename
I need something to happen on the homepage of the websites and not on any of the other pages. Sometimes the homepage has a "something" in the url and sometimes it doesn't, so I need to find out if "pagename" exists, whatever it may be.
all values in the url vary so i can't simply search for a string in the url..
Is this possible to do this using only JS / JQuery?
Thanks
Split is the solution:
var exampleURL = "www.whatever.com/something/pagename";
var pageName = exampleURL.split("/")[2];
console.log(pageName);
//OUT -> pagename
Split the URL and then check the length of the result.
var split_url = url.split('/');
if (split_url.length > 2) {
// URL is like www.whatever.com/something/pagename...
} else {
// URL is just www.whatever.com or www.whatever.com/something
}
Another way is with a regular expression that matches a URL with two slashes:
if (url.match(/\/.*\//)) {
// URL contains two slashes
} else {
// URL has at most one slash
}
You could do a regex check:
/^[^\/\s]*(\/\/)?[^\/\s]+\/[^\/\s]+[^\/]+\/[^\/\s]+$/.test('www.whatever.com/something/pagename')
demo:
https://regex101.com/r/vF1bH8/1
The question is not really clear, but to answer the title literally https://jsfiddle.net/jgfeymk1/
function after2ndFSlash(inpu){
var pieces = inpu.split('/');
var output = document.getElementById('output');
if(pieces.length>2){
output.innerHTML += 'true<br/>';
}
else{
output.innerHTML += 'false<br/>';
}
}
Assuming that url string has protocol included ... http(s):// ... you can pass it to href of an <a> element and access the pathname property
var url ='http://www.whatever.com/something/pagename'
var a = document.createElement('a');
a.href = url;
var pathParts = a.pathname.replace(/^\//,'').split('/');//["something","pagename"]
alert(pathParts[1]); //"pagename"

javascript for splitting url and removing last part

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);

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