Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip / replace something from a URL?

Tags:

javascript

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?

like image 953
JKhan Avatar asked Dec 21 '25 17:12

JKhan


2 Answers

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.

like image 117
Andy Fusniak Avatar answered Dec 23 '25 06:12

Andy Fusniak


You can follow this steps:

  1. split the URL with /
  2. replace the last item of array
  3. 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);
like image 21
Ankit Agarwal Avatar answered Dec 23 '25 05:12

Ankit Agarwal