2017-03-16 70 views
-1

這裏再來javascript noob。Javascript字符串修剪:網址和文件路徑

我想做什麼。 1:

// I will have many URLs as input 
// I want to check if URL NOT end with slash 
// if not then trim string after slash 

var given_URL = "http://www.test.com/test" 

var trimmed_URL = "http://www.test.com/" 

我想做什麼。 2:

// I will have many file paths 
// I would like to check if the path starts with unwanted dot OR slash 
// If so, I would like to trim it 

var given_path_1 = "./folder/filename.xxx" 
var given_path_2 = "/folder/filename.xxx" 
var given_path_3 = ".folder/filename.xxx" 

var trimmed_path = "folder/filename.xxx" 

我想知道如何實現這些。 在此先感謝

+0

你**域後尋找串** –

+0

我試圖消除完成打字量最少的工作領域 – RNA

回答

1

你應該嘗試使用一些regex使用replace()

//replace all "/*" at the end with "/" 
given_URL.replace(/\/\w+$/,'/'); 
//replace all non letters at the start with "" 
given_path_2.replace(/^\W+/,''); 
+0

後字符串= b – RNA

1

要修整直到最後一個正斜槓/,您可以找到它的最後一次出現並檢查它是否是字符串中的最後一個字母。如果是,則直到最後一次出現爲止。

要取出可選點(\.?),其次是從字符串的開始(^)可選的斜槓(\/?),你可以做的^\.?\/?一個正則表達式替換一個。

function trimToLastForwardslash(input) { 
 
    var lastBackSlash = input.lastIndexOf('/'); 
 
    return lastBackSlash != -1 && lastBackSlash != input.length - 1 ? input.substring(0, lastBackSlash + 1) : input; 
 
} 
 

 
function trimFirstDotOrForwardSlash(input) { 
 
    return input.replace(/^\.?\/?/, ''); 
 
} 
 

 
var path = "http://www.test.com/test"; 
 
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path)); 
 

 
path = "http://www.test.com/test/"; 
 
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path)); 
 

 
path = "./folder/filename.xxx"; 
 
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path)); 
 

 
path = "/folder/filename.xxx"; 
 
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path)); 
 

 
path = ".folder/filename.xxx"; 
 
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));

4
  1. 關於第一個問題,你應該使用lastIndexOf方法。

    例如:

    var index = given_URL.lastIndexOf("/"); 
    

    檢查index === given_URL.length - 1是真實的。如果是這樣,你可以使用slice方法來減少你的網址。

    例如:

    var newUrl = given_URL.slice(0,index); 
    
  2. 關於第二個問題,您可以檢查是否given_URL[0] === "."given_URL[0] === "/"。如果這是真的,那麼使用slice方法對其進行分片。

    例如:

    var newUrl = given_URL.slice(1, given_URL.length - 1); 
    
+0

添加4個空格=>將使代碼塊 – RNA

+0

請接受我的答案,如果它幫助你。謝謝 – mv80