3
var dataUrl = $('#AjaxMoreStatus').attr("data-url");

// http://localhost:8888/app/status/get/31/7

I need to change the last value of the link from the last dash (7) by another value. 7 is a dynamic value.

Ho can i do it ?

For instance if i want to change the dynamic value 7 by 9 :

var new = 9;
$("#AjaxMoreStatus").attr("data-url", url without the 7 + '/' + new);
Brian Millot
  • 179
  • 11

5 Answers5

6

use lastIndexOf to check the index of last occurrence of "/"

var dataUrl = $('#AjaxMoreStatus').attr("data-url");

var newValue = 9;

dataUrl = dataUrl.substring( 0, dataUrl.lastIndexOf( "/" ) ) + "/" + newValue;
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
3

Use split() to separate the pieces of the url and replace the last item:

 var url = "http://localhost:8888/app/status/get/31/7";
 url = url.replace("http://", "").split("/");
 var newValue = "9";

 url[(url.length - 1)] = newValue;

 var newUrl = "http://"+url.join("/");
Marcos Pérez Gude
  • 21,096
  • 4
  • 36
  • 67
3

You can use replace method just like here

var url = "http://localhost:8888/app/status/get/31/7";
a.replace(/\/(\d*)$/, '/' + newValue);
mic4ael
  • 7,414
  • 3
  • 29
  • 41
2

If you only need to change the last 7 for other thing, try this code:

var dataUrl = 'http://localhost:8888/app/status/get/31/7';
var newValue = 9;

dataUrl = dataUrl.replace(/([0-9])$/i, newValue);

https://jsfiddle.net/8hf6ra8k/1/

Hope it may help you :).

mrroot5
  • 1,581
  • 3
  • 24
  • 30
1

You can use .lastIndexOf() to find the index. Then you can replace value at that index. For reference, refer following post: How do I replace a character at a particular index in JavaScript?.

var url = "htt[://stacloverflow.com/test/param/tobe/replaced/with/newValue";
var newVal = "testNewValue";

var lastIndex = url.lastIndexOf('/');
var result = url.substring(0,lastIndex+1) + newVal;
alert(result)
Community
  • 1
  • 1
Rajesh
  • 22,581
  • 5
  • 41
  • 70