在jquery中使用连字符拆分字符串后获取最后一个值?
大家好,我将有一个字符串,在中用连字符分隔,我想得到该字符串的最后一个索引,并用新值替换它在jquery中使用连字符拆分字符串后获取最后一个值?,jquery,Jquery,大家好,我将有一个字符串,在中用连字符分隔,我想得到该字符串的最后一个索引,并用新值替换它 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
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,然后得到最后一个长度减1的索引:
var string = "some-hyphen-string";
var parts = string.split("-");
var lastPart = parts[parts.length - 1]; //lastPart is now the final index string split
演示:我必须承认这一点非常不清楚,但也许有了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;
}
jsiddle:使用字符串函数:
var str1 = "New-New_Folder";
var newstr1 = str1.substring(0, str1.lastIndexOf("-")+1) + "Folder";
我已经读了两遍了,我仍然不确定你在问什么。您要替换什么字符串?你想用什么来代替它?