擷取url連結上的參數值的函數

來源:互聯網
上載者:User

標籤:href   cat   返回   component   檢索   url參數   new   arc   ram   

function getUrlParam(name){    var reg     = new RegExp(‘(^|&)‘ + name + ‘=([^&]*)(&|$)‘);    var result  = window.location.search.substr(1).match(reg);    return result ? decodeURIComponent(result[2]) : null;}

其中window.location.search為擷取連結參數的方法,之前一直使用window.location.href然後使用split方法拆分。才發現window.location.search.substr(1)好像更方便。
substr() 方法可在字串中抽取從 start 下標開始的指定數目的字元,substr(1)表示的就是截取?號,擷取?之後的內容。然後用match() 檢索Regex的匹配。

其中正則var reg = new RegExp(‘(^|&)‘ + name + ‘=([^&]*)(&|$)‘); "(^|&)" 這個匹配開頭或&字元,整體表示尋找&+url參數名=值+&的格式,&可以不存在。這樣result的內容就是檢索到的匹配的內容,然後return時判斷是否為空白,如果不為空白則result[2]在這裡表示參數後的值,即返回參數值,如果為空白的話就返回null。

擷取url連結上的參數值的函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.