代码之家  ›  专栏  ›  技术社区  ›  Jack marksy

Javascript substring()技巧

  •  1
  • Jack marksy  · 技术社区  · 15 年前

    我有一个像 http://mysite.com/#id/Blah-blah-blah ,用于Ajax和ey位。我想用 substring() substr() 为了得到 id 部分。 ID 可以是任意长度的字母和数字的任意组合。

    到目前为止,我得到了:

    var hash = window.location.hash;
    alert(hash.substring(1)); // remove #
    

    部分?我也不想要后面的任何东西,包括最后的斜杠( /Blah-blah-blah ).

    谢谢!

    6 回复  |  直到 15 年前
        1
  •  4
  •   ase    15 年前

    现在,正则表达式就有意义了。由于字符串的长度可变,在这里使用子字符串将不起作用。

    此代码将假定id部分不包含任何斜杠。

    var hash = "#asdfasdfid/Blah-blah-blah";
    hash.match(/#(.+?)\//)[1]; // asdfasdfid
    
    • . 将匹配任何字符和
    • 以及 + 一个或多个字符
    • 这个 ? / 在字符串中

    如果id部分可以包含额外的斜杠,并且最后的斜杠是分隔符,那么这个regex将执行您的命令

    var hash = "#asdf/a/sdfid/Blah-blah-blah";
    hash.match(/#(.+?)\/[^\/]*$/)[1]; // asdf/a/sdfid
    

    只是为了好玩,这里的版本不使用正则表达式。

    id部分没有斜杠:

    var hash = "#asdfasdfid/Blah-blah-blah",
        idpart = hash.substr(1, hash.indexOf("/"));
    

    id部分带有斜杠(最后一个斜杠是分隔符):

    var hash = "#asdf/a/sdfid/Blah-blah-blah",
        lastSlash = hash.split("").reverse().indexOf("/") - 1, // Finding the last slash
        idPart = hash.substring(1, lastSlash);
    
        2
  •  1
  •   Darin Dimitrov    15 年前
    var hash = window.location.hash;
    var matches = hash.match(/#(.+?)\//);
    if (matches.length > 1) {
        alert(matches[1]); 
    }
    
        3
  •  1
  •   Paul Creasey    15 年前

    也许是正则表达式

    window.location.hash.match(/[^#\/]+/)
    
        4
  •  0
  •   Raj    15 年前

    使用IndexOf确定/after id的位置,然后使用字符串.substr(开始,长度)以获取id值。

    var hash = window.location.hash;
    var posSlash = hash.indexOf("/", 1);
    var id = hash.substr(1, posSlash -1)
    

    您需要包含一些验证代码来检查是否缺少/

        5
  •  0
  •   Mp0int    15 年前

    这不是一个好办法,但你希望使用如果你想。。。

    var relUrl = "http://mysite.com/#id/Blah-blah-blah";
    var urlParts = [];
    urlParts = relUrl.split("/"); // array is 0 indexed, so 
    var idpart = = urlParts[3] // your id will be in 4th element
    id = idpart.substring(1) //we are skipping # and read the rest 
    
        6
  •  0
  •   Roy Sharon    15 年前

    最简单的方法可能是:

    function getId() {
        var m = document.location.href.match(/\/#([^\/&]+)/);
        return m && m[1];
    }
    

    这段代码不假设任何关于id后面的内容(如果有的话)。它将捕获的id是除正斜杠和符号以外的任何内容。

    如果希望它只捕获字母和数字,可以将其更改为:

    function getId() {
        var m = document.location.href.match(/\/#([a-z0-9]+)/i);
        return m && m[1];
    }