我有以下URL,我想使用JavaScript从中获取“id”值。

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

I started with this code:

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

我想提取ID“ B0077RQGX4 ”,并将其保存到一个变量中,稍后我将对其进行修改。我将如何做以及在JavaScript中使用哪些功能?

最佳答案

我想出了这个:

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'

10-02 20:07