How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3212
天涯浪人
天涯浪人 2020-11-21 06:29

I have seen lots of jQuery examples where parameter size and name are unknown.

My URL is only going to ever have 1 string:

http://example.com?sent=ye         


        
30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:08

    There is another example with using URI.js library.

    Example answers the questions exactly as asked.

    var url = 'http://example.com?sent=yes';
    var urlParams = new URI(url).search(true);
    // 1. Does sent exist?
    var sendExists = urlParams.sent !== undefined;
    // 2. Is it equal to "yes"?
    var sendIsEqualtToYes = urlParams.sent == 'yes';
    
    // output results in readable form
    // not required for production
    if (sendExists) {
      console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
      if (urlParams.sent == 'yes') {
        console.log('"Sent" param is equal to "yes"');
      } else {
        console.log('"Sent" param is not equal to "yes"');
      }
    } else {
      console.log('Url hasn\'t "sent" param');
    }

提交回复
热议问题