2016-11-30 60 views
1

我從 轉換路徑 到如何在JavaScript中轉換路徑?特別是與angularjs?

/modules/useraccounts/client/img/portfolio/uploads/98253cf4f19be659041f55552e5d973d 

modules\useraccounts\client\img\portfolio\uploads\98253cf4f19be659041f55552e5d973d 

/modules/useraccounts/client/img/portfolio/uploads/98253cf4f19be659041f55552e5d973d 

我應該從頭做功能? 我想使用強大的JavaScript和angularjs庫。 以及如何做到這一點? 任何事情都會幫助我! 謝謝。

回答

1

第一種情況只需要slice

if (str[0] === '.') { 
    str = str.slice(1); 
} 

第二種情況,我可能會使用一個RegExreplace

str.replace(/\\/g, '/'); // the 'g' is for global; without it, only the first occurrence is replaced 

這些都是香草JavaScript方法。這裏不需要任何花哨的Angular技巧。

這兩種方法可以被放入一個簡單的函數,如下所示:

function formatPathString (str) { 
    if (str[0] === '.') str = str.slice(1); 
    return str.replace(/\\/g, '/'); 
} 

警告:在正常JS串,反斜線用於轉義/形成特殊字符,所以與反斜線的路徑可能被證明如果反斜槓沒有準確地逃脫,則會出現問題。

換句話說"this\is\a\test".replace(/\\/g, '/')不會導致"this/is/a/test",而是"thisisa\test"因爲\t組合是有意義的,但有些則沒有。您需要確保任何帶反斜槓的傳入字符串已正確轉義,如:"this\\is\\a\\test",以便replace方法按預期工作。

+0

謝謝你,這對我很有幫助 –