大家好我将有一个用连字符分隔的字符串,我想得到字符串的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";
任何人都可以帮助我吗?
答案 0 :(得分:0)
您可以使用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
答案 1 :(得分:0)
我不得不承认这一点非常不清楚,但也许有了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/
答案 2 :(得分:0)
使用字符串函数:
var str1 = "New-New_Folder";
var newstr1 = str1.substring(0, str1.lastIndexOf("-")+1) + "Folder";