2013-08-23 102 views
-1

大家好,我將有一個字符串,在連字符隔開,我想獲得字符串的lastIndex,並與新的價值在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 so that the str becomes 
    var newstr2="New-New_Folder-Sub_Folder"; 

更換任何一個可以幫助我在這裏?

+0

我讀過這兩次,現在,我仍然不能確定你在問什麼。你想要替換什麼字符串?你想用*代替它? –

回答

0

您可以使用拆分,然後獲得與長度減一的最後一個索引:

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/

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/

0

使用字符串函數:

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