【问题标题】:Cut substring after last slash?在最后一个斜杠后剪切子字符串?
【发布时间】:2015-07-29 12:42:28
【问题描述】:

如何从 javascript 中的字符串中删除子字符串(在最后一个斜杠之后)

c:/程序文件/Internet Explorer

到

c:/程序文件/

【问题讨论】:

标签: javascript regex substring


【解决方案1】:

试试 lastIndexOf()

var str = "c:/Program File/Internet Explorer";
var newStr = str.substr(0,str.lastIndexOf("/")+1);

document.getElementById("res").innerHTML = newStr;
<div id="res"/>

【讨论】:

    【解决方案2】:
    var filePath = "c:/Program File/Internet Explorer";
    var displayUptoSpecifiedChar = filePath.lastIndexOf('/') + 1;
    console.log(filePath.slice(0, displayUptoSpecifiedChar));
    

    【讨论】:

    • 在浏览器控制台中查看输出
    【解决方案3】:

    你需要 lastIndexOf 和 substr

    var t = "c:/Program File/Internet Explorer";
    t = t.substr(0, t.lastIndexOf("/"));
    alert(t);
    

    或者您可以使用以下内容。

        var removeLastPart = function(url) 
    {
            var lastSlashIndex = url.lastIndexOf("/");
            if (lastSlashIndex > url.indexOf("/") + 1)
    {
                return url.substr(0, lastSlashIndex);
            } 
    else 
    {
                return url;
            }
        }
    

    【讨论】:

      【解决方案4】:
      var str = "c:/Program File/Internet Explorer";
      var output = str.slice(0, str.lastIndexOf("/")+1);
      

      【讨论】:

        【解决方案5】:

        如果您想测试正则表达式,请查看http://www.regexr.com。 .*/ 之类的东西会将所有内容匹配到斜杠字符。

        【讨论】:

          【解决方案6】:

          您可以尝试以下基于否定字符类的正则表达式。

          string.replace(/[^\/]*$/, "")
          

          DEMO

          • [^\/]* 匹配任何字符,但不匹配正斜杠零次或多次。

          • $ 断言我们在行尾。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-12-07
            • 1970-01-01
            • 2012-12-02
            • 1970-01-01
            • 2013-08-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多