Remove only the part after url and before # - javascript

In address bar: http://xxx/view/9204?category=bed#details
Javascript:
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
Found the snippet online, but it cut off the stuff after url. Wanted to take out only ?category=bed part. Is there any way to take that part?
Want the string: http://xxx/view/9204#details

You could replace the search part of the url with nothing, like this:
var yourURL = window.location.href.replace(window.location.search,'');
According to this site:
window.location.search - Returns the query portion of the URL, including the question mark
window.location.href - Returns the entire URL.

How about this, add the two substring fragments together:
var clean_uri = uri.substring(0 , uri.indexOf("?")) + uri.substring(uri.indexOf("#"));

Related

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

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

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