【问题标题】:Get value after string slash from current url javascript [duplicate]从当前网址javascript获取字符串斜杠后的值[重复]
【发布时间】:2017-08-04 08:37:19
【问题描述】:

我有一个如下所示的当前页面网址:

http://localhost/admin/namespace_module/yeezy/index/test_id/5/key/23123asda/

网址可以是动态的,但总是包含 /test_id/value/ ,首先我想检查 /test_id/ 是否存在在我当前的网址中:

window.location.href

然后我需要检索值

【问题讨论】:

    标签: javascript regex url


    【解决方案1】:

    使用RegExp#test 方法。

    if(/\/test_id\//.test(window.location.href)){
    
    }
    

    或使用String#indexOf 方法。

    if(window.location.href.indexOf('/test_id/') > -1){
    
    }
    

    【讨论】:

    • 那么我怎样才能检索斜线后的值?
    • @IdhamChoudry:window.location.href.split('/test_id/').pop()
    【解决方案2】:

    你可以用正则表达式结合.test()检查和.match()提取数字:

    var url = "http://localhost/admin/namespace_module/yeezy/index/test_id/5/key/23123asda/"; // window.locatioin.href;
    
    if(/test_id\/[0-9]+/.test(url)){
       console.log(url.match(/test_id\/[0-9]+/)[0].match(/[0-9]+/)[0]);
       //--test_id/5---------^^^^^^^^^^^^^^^^^^^^^----5--^^^^^^^^^^^^
    }  //--output-----------------------------------output-----------

    【讨论】:

    • 这种方法的缺点是效率不高。一个正则表达式最多可以执行 3 次,而一个正则表达式可以执行一次。
    【解决方案3】:

    要在测试模式后获取数字,请执行以下操作:

    var match = window.location.href.match(/\/test_id\/(\d+)/);
    if (match) {
        // pattern is OK, get the number
        var num = +match[1];
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2015-06-21
      • 2015-06-18
      • 1970-01-01
      相关资源
      最近更新 更多