Javascript 字符串修剪:Url 和文件路径

Javascript string trimming: Url and file path

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"

我想知道如何实现这些。 提前致谢

到trim直到最后一个正斜杠/,你可以找到它的最后一次出现并检查它是否是字符串中的最后一个字母。如果是,则在最后一次出现之前取字符串。

要从字符串的开头 (^) 删除一个可选的点 (\.?),然后是一个可选的正斜杠 (\/?),您可以进行替换正则表达式 ^\.?\/?.

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));

你应该尝试使用 replace() using some regex:

//replace all "/*" at the end with "/"
given_URL.replace(/\/\w+$/,'/');
//replace all non letters at the start with ""
given_path_2.replace(/^\W+/,'');
  1. 对于你的第一个问题,你应该使用lastIndexOf方法。

    例如:

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

    检查 index === given_URL.length - 1 是否为真。如果是,您可以使用slice 方法来削减您的url。

    例如:

    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);