By GokiSoft.com| 19:26 30/10/2021|
Tài Liệu Javascript

Làm thế nào để lấy giá trị các tham số trong URL (How can I get query string values in JavaScript?)

Làm thế nào để lấy giá trị các tham số trong URL (How can I get query string values in JavaScript?)

Các bạn có thể sử dụng đoạn code sau để lấy ra giá trị của các tham số


function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Ví dụ sử dụng


// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

Ví dụ khác

var url = https://gokisoft.com/?programming&id=13&path=1-Huong-dan-tat-debug-khi-upload-du-an-laravel-len-HOST

var id = getParameterByName('id', url);//13
var path = getParameterByName('path',url);//1-Huong-dan-tat-debug-khi-upload-du-an-laravel-len-HOST


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)