在jquery中使用连字符拆分字符串后,获取最后一个值



嗨,我将在中有一个用连字符分隔的字符串,我想获得字符串的lastindex并用新值替换它

   var str1="New-New_Folder"; //Replace New_Folder with Folder so that the str becomes
   var newstr1="New-Folder";

   var str2="New-New_Folder-New_Folder"; //Replace the last New_Folder with Sub_Folder so that the str becomes
   var newstr2="New-New_Folder-Sub_Folder";

这里有人能帮我吗?

您可以使用split,然后获得长度减一的最后一个索引:

var string = "some-hyphen-string";
var parts = string.split("-");
var lastPart = parts[parts.length - 1]; //lastPart is now the final index string split

演示:http://jsfiddle.net/ACfRU/

我不得不承认这一点非常不清楚,但也许有了tymeJV和我的答案,你可以想出一个适合你需求的解决方案。

var str1="New-New_Folder";
var newstr2 = replaceLast(str1, "Sub_Folder");
alert(newstr2);
function replaceLast(strWhat, strWith) {
    strWhat = strWhat.split("-");
    strWhat[strWhat.length - 1] = strWith;
    strWhat = strWhat.join("-");
    return strWhat;
}

JSFiddle:http://jsfiddle.net/FF96g/

使用字符串函数:

var str1 = "New-New_Folder";
var newstr1 = str1.substring(0, str1.lastIndexOf("-")+1) + "Folder";

最新更新