display current subdirectory URL of webpage - javascript

Having an issue with the following code, it displays the full URL of the current page, (eg, example.com/dir1) however I am looking to display the sub directories only (eg, /dir1/). Also having an issue where it does not display spaces properly, spaces show in html encoding %20. I have very little programming experience and any help would be greatly appreciated.
<p3><script>document.write(location.href);</script></p3>
EDITworking on the following script, however am having trouble implementing it
<script>str.replace("%20", " ")</script>any thoughts?
EDIT - answer which suited my needs, many thanks to brettc
var url = location.href;
url = url.split("examle.com").pop();
url = decodeURIComponent(url);
document.write(url);

This may not be the best way, but a way none the less.
You could just split the string by the ”/“ and take the last occurrence.
Also, decodeURIComponent() will decode the %20 to a space, as found here.
<script>
var url = location.href;// get url, put in url variable
url = url.split("/").pop();// get last element separated by “/“
url = decodeURIComponent(url);// remove any %20
alert(url);
</script>
Note: this will alert everything past the last “/“.

Related

How to grab URLs in JavaScript without harming embedded objects and inline URL

I wrote a RegExp to grab and encode URLs in JavaScript.
This works fine but, it introduced a bug into my app.
I have a span Element which is used to display Emojis like this:
<span style="background:url(http://localhost/res/emo/face/E004.png)"></span>
Now, I'm using this Regular Expression to grab and convert anything URL into actual HTML clickable links:
/((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/ig
This ended up encoding the emoji URL into a clickable link.
Can anyone adjust that Code to Ignore URLs inside Elements or embedded Objects???
Please I need help!
This is the code:
var urlRegex = /((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/ig;
return txt.replace(urlRegex, function (url) {
var hyperlink = url;
if(!hyperlink.match('^https?:\/\/')) {
hyperlink = 'http://' + hyperlink;
}
return `${url}`;
});
I don't that the URLS inside
<span style="background:url(http://localhost/res/emo/face/E004.png)"></span>
were touched.
You would need to use negative look behind, which has limited support in JavaScript. (see here https://stackoverflow.com/a/50434875/6853740)
Simply adding negative look behind to your existing regex still doesn't work as expected:
((?<!url\()(https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?) still matches "E004.png" in your example. Even other URL regexs from this post (What is the best regular expression to check if a string is a valid URL?) also match that. You may need to consider only looking for links that start with http:// or https:// which may help you recraft a regex that will only match full URLs.

How to replace the forward slash in a javascript bookmarklet

I am not a programmer, but know a little here and there. This is a bookmarklet I have in my browser. It is supposed to take the url of the page I am on, and when clicked, takes me to another site (example.com), and pass this first site into the url of the second site (e.g. sitechecker.com).
Problem is, the trailing slash on the example.com/ prevents sitechecker from working, so i need to get rid of the trailing slash somehow when its passed to the other site.
E.g.
No Good
http://www.example.com/
Good
http://www.example.com
Bookmarklet code:
javascript:(function(){ var url=location.href; var url=url.replace(/^(http|https):\/\//i,''); window.open('https://www.widgetfactory.com/index.html/all//'+encodeURIComponent(url)+'/Oc?l=us')})();
Try the following regex url.replace(/\/$/, ""); Exm. below
var url = 'http://www.example.com/';
console.log(url.replace(/\/$/, ""));

How to remove URL from a string completely in Javascript?

I have a string that may contain several url links (http or https). I need a script that would remove all those URLs from the string completely and return that same string without them.
I tried so far:
var url = "and I said http://fdsadfs.com/dasfsdadf/afsdasf.html";
var protomatch = /(https?|ftp):\/\//; // NB: not '.*'
var b = url.replace(protomatch, '');
console.log(b);
but this only removes the http part and keeps the link.
How to write the right regex that it would remove everything that follows http and also detect several links in the string?
Thank you so much!
You can use this regex:
var b = url.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
//=> and I said
This regex matches and removes any URL that starts with http:// or https:// or ftp:// and matches up to next space character OR end of input. [\n\S]+ will match across multi lines as well.
Did you search for a url parser regex? This question has a few comprehensive answers Getting parts of a URL (Regex)
That said, if you want something much simpler (and maybe not as perfect), you should remember to capture the entire url string and not just the protocol.
Something like
/(https?|ftp):\/\/[\.[a-zA-Z0-9\/\-]+/
should work better. Notice that the added half parses the rest of the URL after the protocol.

JavaScript unable to get fragment when splitting URL

I have limited JS experience, and I need to split a string that would look something like:
http://example.com/#!/about
Into http://example.com/ and !/about
I can't unfortuently use PHP and parsing the URL won't work. Right??
This is what I have at the moment:
<script type="text/JavaScript">
var newUrl = window.location.pathname;
var hash=newUrl.split('#');
var f=hash[1];
</script>
I could do this for the 3rd line:
var hash=newUrl.split('com');
And then account for the hash, but the problem with that is if someone goes to
example.com/index.php/#!/about
So I'd then have to double my code after this point.
Any ideas how to split the URL into two parts centring around the hash without having to use what I just mentioned??
The .pathname doesn't include the hash. Use the .hash property instead. Use substring to strip the # character from the front.
var hash = location.hash.substring(1);
If it's not your window.location, you can use /([^:]+://[^/]+)[^#]+#(.*)/ - you will get the required parts in the first and second capturing groups.

javascript how to switch pathname of window.location property and redirect

I want to redirect a user from varying urls to a specific one. I've tried various flavors of replacing and I cant seem to get the behavior I want. This code works except I'm providing the hostname. I want to use the existing hostname from windows.location.hostname and just provide a new pathname. Sometimes the urls vary in size and slashes ('/').
window.location = 'http://localhost:36065/NewPath';
How would I change these urls?
http://somesite.com/xxx/yyy/zzz to http://somesite.com/NewPath
http://somesite.com/xxx/yyy to http://somesite.com/NewPath
http://somesite.com/xxx to http://somesite.com/NewPath
I think you get the point. The path can vary in paths, I want to replace everything after .com basically with 'NewPath'
I'd like a clean regex solution if possible but I am quite the rookie in that dept. Thanks for any tips or tricks.
location.pathname = '/newpath.html'
You could always use the various location properties to recreate the part you need and append the new part to it:
window.location = location.protocol + "//" + location.hostname + "/NewPath";
Just to show the hard way:
// Find everything up to the first slash and save it in a backreference
regexp = /(\w+:\/\/[^\/]+)\/.*/;
// Replace the href with the backreference and the new uri
newurl = windows.location.href.replace(regexp, "$1/dir/foo/bar/newpage.html");

Categories

Resources