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

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"

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

Remove only the part after url and before #

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("#"));

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

JavaScript: How to Strip out everything and just get the ID?

I'm creating a Bookmarklet for YouTube, i want to get the ID from the youtube link,
Ex: http://www.youtube.com/watch?v=YgFyi74DVjc
I want only "YgFyi74DVjc" from the above link, that's just an example of what i want, it has to strip out everything and just leave that end part, another thing is
i want to get the ID from this URL as well
http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]
So basically when you click on some video and then on this bookmarklet it gets the youtube video ID and redirects them to a link which unlocks the video or expands the video to full size of the user's browser, i have everything coded and just need a way to get ID's from both the links, i have coded this which works for the 2nd link
var url = "http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]";
var ytcode = url.substr(80,50);
alert(ytcode);
Now i want someway to get ID's from both the links, please help!
This is a job for regex:
url.match(/(\?|&)v=([^&]+)/).pop()
which, broken down, means:
url.match(
// look for "v=", preceded by either a "?" or a "&",
// and get the rest of the string until you hit the
// end or an "&"
/(\?|&)v=([^&]+)/
)
// that gives you an array like ["?v=YgFyi74DVjc", "?", "YgFyi74DVjc"];
// take the last element
.pop()
You can use this for the second form as well if you decode it first:
url = decodeURIComponent(url);
The url variable now equals "http://www.youtube.com/verify_age?next_url=http://www.youtube.com/watch?v=[YOUTUBEID]", and the regex should work.
You could put it all together in a reusable function:
function getYouTubeID(url) {
return decodeURIComponent(url)
.match(/(\?|&)v=([^&]+)/)
.pop();
}
Assuming the ID (i.e. the v parameter) is always the last parameter in the URL:
url = url.replace("%3D", "=");
var splitUrl = url.split("=");
var yId = splitUrl[splitUrl.length - 1];
The replace function is used to replace the character code %3D with =, which is what it represents. You can then split the string on the = character, and your ID will be the last element in the resulting array.
You could use this function (just pass it the url and the name of the parameter)
function getParameterByName( name, url )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url = "http://www.youtube.com/watch?v=YgFyi74DVjc"
var v= getParameterByName('v', url);
Slight modification to nrabinowitz answer to allow for YouTube share URLs such as:
http://youtu.be/3Ah8EwyeUho
Also i have attached it to a class so it can be easily reused.
$(function(){
$('.js-youtube').on('blur', function(){
var newval = '';
if (newval = $(this).val().match(/(\?|&)v=([^&#]+)/)) {
$(this).val(newval.pop());
} else if (newval = $(this).val().match(/(youtu\.be\/)+([^\/]+)/)) {
$(this).val(newval.pop());
}
});
});

Categories

Resources