简体   繁体   中英

JavaScript/Jquery Regexp Replace

I'm doing a hovercard plugin for my site but have a problem with getting user id.

profile urls can be;

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

etc..

How can I get profiles' id by javascript Regexp Replace?

    $(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]

This has been tested on http://www.regular-expressions.info/javascriptexample.html

I would do it like this:

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];
}

Then to get the id it's as simple as params.id

Here's how you can get the URL for the current link:

$('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);
    }, 

And then to match the regular expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM