Add "/path/" in the middle of an URL in JavaScript - javascript

How can I effectively add a "path" to the middle of an URL in JavaScript?
I want to add embed to an URL, so the URL https://blog.com/post/123 will end up looking like this https://blog.com/embed/post/123?
Cheers

You can create an <a> and set the href property. Then prepend embed to the pathname and use toString() to get the whole URL.
let element = document.createElement('a');
element.href = 'https://blog.com/post/123';
element.pathname = 'embed' + element.pathname;
console.log(element.toString());

You can do this, if the path is just a string
var path = "https://blog.com/post/123";
var withEmbed = path.replace(/\/post\//,'/embed/post/');
console.log(withEmbed);

You can use the location API.
https://developer.mozilla.org/en-US/docs/Web/API/Location
function addEmbed(location) {
return location.protocol + '//' + location.host +
'/embed' + location.pathname;
}
var url = document.createElement('a');
url.href = 'https://blog.com/post/123';
var embed = addEmbed(url);
console.log(embed); // "https://blog.com/embed/post/123"
Example: https://codepen.io/anon/pen/wXxvaq

The way i would do it, is to pass by ref/value the original URL and the text you wan to add, into a function. It then removes the "https://" (if necessary), splits the url at the first "/" and saves each part as a var. Finally it puts it all back together and outputs it to a on the html page.
This doesnt have to be outputted in this way, it could be saved as a global variable and then used in a link (but i didn't know what your plan was so i outputted it) :)
function addToURL(URL, add) {
URL = URL.replace(/(^\w+:|^)\/\//, '');
var part1 = URL.substring(0, URL.indexOf("/") + 1);
var part2 = URL.substring(URL.indexOf("/"), URL.length);
var result = "https://" + part1 + add + part2;
document.getElementById("demo").innerHTML = result;
}
Here's the example I made: https://codepen.io/anon/pen/RJBwZp
Hope this helps :P

Related

add to URL after last /

using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.

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

How to get url path without $_GET parameters using javascript?

If my current page is in this format...
http://www.mydomain.com/folder/mypage.php?param=value
Is there an easy way to get this
http://www.mydomain.com/folder/mypage.php
using javascript?
Don't do this regex and splitting stuff. Use the browser's built-in URL parser.
window.location.origin + window.location.pathname
And if you need to parse a URL that isn't the current page:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
console.log(url.origin + url.pathname);
And to support IE (because IE doesn't have location.origin):
location.protocol + '//' + location.host + location.pathname;
(Inspiration from https://stackoverflow.com/a/6168370/711902)
Try to use split like
var url = "http://www.mydomain.com/folder/mypage.php?param=value";
var url_array = url.split("?");
alert(url_array[0]); //Alerts http://www.mydomain.com/folder/mypage.php
Even we have many parameters in the GET , the first segment will be the URL without GET parameters.
This is DEMO
try this:
var url=document.location.href;
var mainurl=url.split("?");
alert(mainurl[0]);
Try
var result = yourUrl.substring(0, yourUrl.indexOf('?'));
Working demo
var options = decodeURIComponent(window.location.search.slice(1))
.split('&')
.reduce(function _reduce (/*Object*/ a, /*String*/ b) {
b = b.split('=');
a[b[0]] = b[1];
return a;
}, {});

Replace filename using JavaScript?

Can someone show me how to do the following in JavaScript? I know how to grab the src of the image, I just want to be able to replace the filename with something new.
/image/any/path/ANY-TEXT_HERE.png
/image/any/path/NEWTEXT.png
Case-insensitive version:
path = path.replace(/(.*)\/.*(\.png$)/i, '$1/NEWTEXT$2')
Remove the i after / to make it case-sensitive.
Another option:
var filename = "/image/any/path/NEWTEXT.png";
var splitFilename = filename.split("/");
var newPath = splitFilename.slice(0, splitFilename.length - 1).join("/")
if (newPath.length !== 0) {
newPath += "/"
}
newPath += newFilename;
All the other solutions so far assume there actually IS a path. They work only if there is at least one forward slash. This tested functions works in all cases including an empty path:
function rename_img_file(text, newname)
{ // Rename file in a IMG src (no query or fragment)
var re = /^(.*\/)?[^\/]+\.(png|gif|jpe?g)$/i;
var rep_str = '$1' + newname + '.$2';
text = text.replace(re, rep_str);
return text;
}
var url = "/image/any/path/ANY-TEXT_HERE.png";
var mystring = "NEWTEXT";
var ind1 = url .lastIndexOf('/');
var ind2 = url .lastIndexOf('.');
var new_url = url.substring(0,ind1+1 )+ mystring + url.substring(ind2 );
alert(new_url );
javascript its really restrictive to files.
I assume that you want to do that on a server. if that so, you should use a serverside script, not a client side.
Maybe you ar talking about an ajax script
if you can explain a ltl further maybe i can lendyou a hand

Categories

Resources