【问题标题】:Javascript string trimming: Url and file pathJavascript字符串修剪:网址和文件路径
【发布时间】:2017-03-16 07:01:02
【问题描述】:

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"

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

【问题讨论】:

  • 您是否在寻找 domain 之后的字符串
  • 我正在尝试消除域后的字符串

标签: javascript string syntax trim


【解决方案1】:
  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);
    

【讨论】:

    【解决方案2】:

    您应该尝试使用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+/,'');
    

    【讨论】:

      【解决方案3】:

      要修剪直到最后一个正斜杠/,您可以找到它的最后一次出现并检查它是否是字符串中的最后一个字母。如果是,则将字符串保留到最后一次出现之后。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        相关资源
        最近更新 更多