簡體   English   中英

JavaScript / Jquery正則表達式替換

[英]JavaScript/Jquery Regexp Replace

我正在為我的網站做一個懸浮卡插件,但是在獲取用戶ID時遇到問題。

個人資料網址可以是;

hxxp://mysite.com/?p=profile&id=1
hxxp://mysite.com/?p=profile&id=1&page=2
hxxp://mysite.com/?p=profile&id=1&v=wall

等等..

如何通過javascript Regexp Replace獲取配置文件的ID?

    $(document).ready(function () {
    var timer;
    $('a[href*="hxxp://mysite.com/?p=profile"]').hover(
        function () {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer =  setTimeout(function() {

              // profile_id
              // and get id's hovercard content here

            },1000);
        }, 
        function () {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            $('.HovercardOverlay').empty();
        }
        );
}); 
var result = $(this).attr("href").match(".*profile&id=(\d+)&?.*")
var id = result[1]

已在http://www.regular-expressions.info/javascriptexample.html上進行了測試

我會這樣做:

var url = "hxxp://mysite.com/?p=profile&id=1&v=wall"; // this.href or w/e
var paramsArray = url.match("[?].*")[0].substr(1).split("&");
var params = {};
for (var i in paramsArray)
{
    var parts = paramsArray[i].split("=");
    params[parts[0]] = parts[1];
}

然后獲取id就像params.id一樣簡單

以下是獲取當前鏈接的URL的方法:

$('a[href*="hxxp://mysite.com/?p=profile"]').hover(
    function () {
        if(timer) {
            clearTimeout(timer);
            timer = null
        }
        timer =  setTimeout(function() {

          // profile_id
          var myUrl = $(this).attr("href");

          // and get id's hovercard content here

        },1000);
    }, 

然后匹配正則表達式:

> var myUrl = "hxxp://mysite.com/?p=profile&id=5";
> var pattern = new RegExp("id=([0-9]+)");
> pattern.exec(myUrl);
["id=5", "5"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM