add to URL after last / - javascript

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.

Related

Add "/path/" in the middle of an URL in 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

Regex not working to remove string/whatever

How can I remove this string from href and update it ?
Example Url:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"
What I am trying:
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);
What I want:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"
Update
Please don't hard code
If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g
Take a note that RegExp is written as is - without surrounding it with quotes.
var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';
console.log(str.replace(/Products\/\w+,?/g, ''));
/**
* Replace with variable string
*/
var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
$("#qUrl").attr("href", url);
Modify the replace call , use regex without quotes

Javascript, insert string into another URL string

Not sure how I would go about writing a formula to do this... I need to do:
current_url = "http://something.random.com/something/something/upload/something/something_else"
new_url = "http://something.random.com/something/something/upload/{NEWSOMETHING}/something/something_else"
Basically I'm always trying to insert another string segment exactly after the upload/ in the original URL. I've thought about using position but I don't have a fixed position because current_url won't always be the same length. The only constant is that I know the string needs to be inserted after upload/, wherever it may be
current_url.replace("upload/","upload/{NEWSOMETHING}/")
If your string is var current_url = "http://something.random.com/something/something/upload/something/c_fit/something_else/c_fit/"; and you want to replace everything in between upload and the last c_fit then current_url.replace(/\/upload\/.*\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/") but you just want to replace between upload and the first c_fit then current_url.replace(/\/upload\/.*?\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/")
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var chunks = current_url.split("/");
var str = [];
var s = chunks.shift();
while(s != "upload"){
str.push(s);
s = chunks.shift();
}
var new_url = str.join('/')+"/upload/{new something}/something/something_else";
alert(new_url);
You could easily split the string on the static text "upload".
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var splitArray = current_url.split("upload");
var additionalParameter = "What_ever_comes_after_upload"
var new_url = splitArray[0] + "upload/" + additionalParameter + splitArray[1];
alert(new_url);

remove a specific area from url using jquery

I have a URL such as http://myurleg.com/ar/Message.html and I want to replace ar with en in it, after clicking on it.
It means that if my url is: http://myurleg.com/ar/Message.html
After click it should become: http://myurleg.com/en/Message.html
I just tried
<script>
$(document).ready(function () {
$('#lng_flip').click(function () {
var url = window.location.href.split('/')[0];
});
});
</script>
Can anyone help?
You can user string replace :
var str = "http://myurleg.com/ar/Message.html";
document.write(str);
var res = str.replace("/ar/", "/fr/");
document.write('<br /> Result : ' + res );
var current = location.pathname.substring(1, 3);
var flipped = current == 'en' ? 'ar' : 'en';
location.pathname = '/' + flipped + location.pathname.substring(3);
Try this
var str = 'http://myurleg.com/ar/Message.html';
var txt = str.replace(/ar/i,"en");
Or in your case
var url = window.location.href;
window.location.href = url.replace(/ar/i,"en");
A general solution, supporting any two-letter language code at the beginning of the path, would be:
location.href = location.href.replace(/(\/\/.*?\/)\w{2}(.*)/, '$1en$2');
Though sometimes it makes more sense to only manipulate location.pathname:
location.pathname = location.pathname.replace(/\/\w{2}(.*)/, '/en$1');
Replace ar in split('/') array with en and join it again using join('/')
var url ='http://myurleg.com/ar/Message.html'.split('/');
url[3]='en';
url=url.join('/');
document.write(url);

Remove sections of url to only keep file name

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);
You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle
You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

Categories

Resources