4

次のURLがあり、JavaScriptを使用してそこから「id」値を取得したいと思います。

https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go

私はこのコードから始めました:

var url = document.URL;
var id_check = /^\id...\E; // NOT SURE HERE
var final_id = new RegExp(id_check,url);

ID「B0077RQGX4」を抽出して、後で変更する変数に保存したいと思います。どのようにそれを行い、JavaScriptでどの関数を使用しますか?

4

6 に答える 6

17

私はこれを思いついた:

var final_id;
var url = document.URL;
var id_check = /[?&]id=([^&]+)/i;
var match = id_check.exec(url);
if (match != null) {
    final_id = match[1];
} else {
    final_id = "";
}

対象:

https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?SomethingElse=Something&id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?commit=go&id=B0077RQGX4
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?commit=Go
final_id = ''

https://www.blabla.com/ebookedit?id=1234&Something=1&id=B0077RQGX4&commit=Go
final_id = '1234'
于 2012-04-12T15:56:37.937 に答える
4

While you can do this with Regex, it's probably going to be easier and/or more consistent if you use a non-Regex approach. This is the case because the query string could have a wide variety of layouts (with the id value first, last, or in the middle).

EDIT: @AdrianaVillafañe proves that this can be done easily with a Regex! I'm going to leave this JS-only method here because it does work.

I like to use this JavaScript method to parse query string from a URL and get the first value that matches the desired name. In your case, "id" would be the name parameter.

// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
    if (query.indexOf("?") == 0) { query = query.substr(1); }
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split("=");
        if (pair[0] == name) {
            return pair[1];
        }
    }
    return "";
}

To use this method, you would pass in the query string portion of the URL and the name of the value that you want to get. If you want to parse the URL of the current request, you could do this:

var value = GetQueryVariable(location.search, "id");

Trying to do this in a Regex will most likely be inconsistent at best when trying to handle the possible variations of the query string layout.

于 2012-04-12T15:51:20.290 に答える
1

これを試してみてください。

function getUrlVars()
{
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value)   
  {
     vars[key] = value;
  });
  return vars;
} 


function urlval()
{
    var x=getUrlVars()["id"];
    alert (x);
 }

x は ID に B0077RQGX4 の値を与えます。

于 2013-04-25T13:29:09.523 に答える
0

このようなものがうまくいくはずです。

var url = document.URL;
var regex = new RegExp("id=(.+)&");

var id = url.match(regex)[1];​​​​​​

jsfiddle の例はこちらです。

于 2012-04-12T15:44:40.030 に答える
0

それは正規表現ではありませんが、あなたはただ行うことができます

id=url.split('id=')[1].split('&')[0];
于 2012-04-12T15:28:53.177 に答える