JKhan
JKhan

Reputation: 1287

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?

Upvotes: 2

Views: 139

Answers (5)

Randy
Randy

Reputation: 9809

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

Upvotes: 1

Andy Fusniak
Andy Fusniak

Reputation: 1638

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.

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

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.

Upvotes: 2

kshetline
kshetline

Reputation: 13682

You could use a regular expression like this:

let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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

Upvotes: 2

Related Questions