Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否替换数据属性中的最后一个破折号值?_Javascript_Jquery - Fatal编程技术网

Javascript 是否替换数据属性中的最后一个破折号值?

Javascript 是否替换数据属性中的最后一个破折号值?,javascript,jquery,Javascript,Jquery,我需要将链接的最后一个值从最后一个破折号(7)更改为另一个值。 7是一个动态值 我能做什么 例如,如果要将动态值7更改为9: var dataUrl = $('#AjaxMoreStatus').attr("data-url"); // http://localhost:8888/app/status/get/31/7 使用lastIndexOf检查上次出现的“/”的索引 使用split() var dataUrl = $('#AjaxMoreStatus').attr("data-url"

我需要将链接的最后一个值从最后一个破折号(7)更改为另一个值。 7是一个动态值

我能做什么

例如,如果要将动态值7更改为9:

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

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

使用
lastIndexOf
检查上次出现的“/”的索引

使用
split()

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

var newValue = 9;

dataUrl = dataUrl.substring( 0, dataUrl.lastIndexOf( "/" ) ) + "/" + newValue;

您可以像这里一样使用
replace
方法

 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("/");

您可以使用
.lastIndexOf()
查找
索引。然后可以替换该索引处的值。如需参考,请参阅以下帖子:

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;

警报(结果)
如果您只需要为其他事情更改最后7个,请尝试以下代码:

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

希望它可以帮助您:)。

我也想到了
split()
,但就是想不出替换上一个值:)
var url = "http://localhost:8888/app/status/get/31/7";
a.replace(/\/(\d*)$/, '/' + newValue);
var dataUrl = 'http://localhost:8888/app/status/get/31/7';
var newValue = 9;

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