how to add string to url before the last string - javascript

I am want add string in between the url
I have an url
hostname.com/test1/test
I want to add test2 before the test
it should be hostname.com/test1/test2/test
Do I need break the strings with / and then again build the string by adding tests?
Or is there any other way I can work on?

var url ="hostname.com/test1/test";
var lastSlash = url.lastIndexOf("/");
var output = url.substring(0,lastSlash) + "/test2" + url.substring(lastSlash, url.length);
console.log(output);
Hope this helps.

var url = 'hostname.com/test1/test';
var urlParts = url.split('/');
urlParts.splice(urlParts.length-1, 0, "test2");
alert(urlParts.join('/'));

Related

Add new Param URL in the middle using javascript

Sorry for asking simple questions.
I have url with like this :
http://sub.maindomain/page/title
I want to add
/en/
in the middle of my url so it will be change to
http://sub.maindomain/en/page/title
thank you for your help
var str='http://sub.maindomain/page/title';
var en='en/';
var position= str.indexOf('page')
alert(str.substr(0, position) + en + str.substr(position));
i guess there will be always page in that url so i found it's index,
and added en before it's index
If you want to change the actual URL with a new URL parameter en in the address bar. You can try this.
var newUrl = location.origin + '/en' + location.pathname
document.location.href = newUrl
Supposing you're in a context where document is available (since your post is taggued jQuery, it's most likely the case):
const href = 'http://sub.maindomain/page/title?foo=bar#hash';
// Build a link element
const link = document.createElement('a');
link.href = href;
// Add '/en' before its pathname
const result = link.protocol + '//' + link.host + '/en' + link.pathname + link.search + link.hash;
console.log(result);
in case if page is not on after domain some other string is there then try below code.
var str = 'http://sub.maindomain/page/title';
var arr = str.split(/\//);
arr.splice(3, 0, 'en');
str = arr.join('/');
let url = "http://sub.maindomain/page/title";
let textToAdd = "en/";
//Split the url string into array of two elements and then join them together with a new string 'en/page' as a separator
let newUrl = url.split('page').join(`${textToAdd}page`);
console.log(newUrl);

How to strip / replace something from a URL?

I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

How to parse a url using Javascript and Regular Expression?

I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.

Extract last string of a URL

I have a URL like this:
http://www.url/name/something/#/venue
I need to grab the 'venue' from each URL. I have:
var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );
The split breaks up the URL.
I'm not sure how to grab the last part of urlParts.
urlParts[urlParts.length - 1];
Just grab the last element of the urlParts array:
var lastPart = urlParts[urlParts.length - 1];
Instead of $(location) why not just use location object and location.hash? Like this:
location.hash.replace('#/', '')
For url like http://www.url/name/something/#/venue it will give you venue.
You can get it like this:
var url = document.URL.split('#/')[1];
var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );
alert(urlParts[urlParts.length-1]);
The fiddle here.
To grab the last element in the array urlParts, just use:
var last = urlParts[urlParts.length-1];
As an alternate way to do this, you could do:
var last = currentUrl.substr( currentUrl.lastIndexOf("/")+1 );

Javascript parsing Url

I have a Url which is like this.
https://testOne.abcd.com/myOrders/OrderList/Order123.aspx
How do I get only Order123 ?
I used window.location.href.split('/')[5].split('/')[1]
how do i set it dynamically?
TIA
if you want to use substr string method..
var filename = url.substr(url.lastIndexOf('/')+1) // -> 'Order123.aspx'
var filename_noext = filename.substr(0, filename.lastIndexOf('.')) // -> 'Order123'
If you want to get the file name, minus the extension, this will work.
var regex = /.*\/([^\/]+)\.aspx/;
var url = 'https://testOne.abcd.com/myOrders/OrderList/Order123.aspx'
var match = regex.exec(url);
var fileName = match[1];
alert(fileName); // This will output "Order123"

Categories