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

时间:2017-03-16 07:01:03

标签: javascript string syntax trim

这里再次出现javascript noob。

我想做什么。 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"

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

3 个答案:

答案 0 :(得分: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);
    

答案 1 :(得分: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));

答案 2 :(得分:1)

您应该尝试使用replace()使用regex

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