sách gpt4 ai đã đi

javascript - 获取 URL 参数函数,获取 url 部分的值,或者如果存在但没有值则返回 true?

In lại 作者:行者123 更新时间:2023-12-02 20:37:09 32 4
mua khóa gpt4 Nike

我正在使用以下函数来获取 URL 参数。

function gup(name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var results = new RegExp('[\\?&]'+name+'=?([^&#]*)').exec(url || window.location.href);
return results == null ? null : results[1];
}

例如,仅当参数具有值时它才有效。

gup('a', 'http://example.com/page.php?a=1&b=2');

将返回 1。但是如果我尝试

gup('a', 'http://example.com/page.php?a&b=2');

它返回 null。我希望它返回 true,因为参数“a”存在于该 url 中,即使它没有值,但它仍然存在,并且 gup() 应该返回 true。我可以得到一些帮助来重写这个吗?我不太擅长正则表达式。

1 Câu trả lời

对于第二个示例,它实际上不返回 vô giá trị,它返回一个空字符串。

空字符串是falsy,它们在 bool 上下文中强制为SAI,因此您可以在三元组的第二个分支中使用它。

在那里,您知道某些内容已匹配(在 results[1] 中),并且仅当匹配为 falsy 时,您才能返回 ĐÚNG VẬY (空字符串):

function gup(name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var results = new RegExp('[?&]'+name+'=?([^&#]*)').exec(url || window.location.href);
return results == null ? null : results[1] || true;
}

gup('a', 'http://example.com/page.php?a&b=2'); // true
gup('a', 'http://example.com/page.php?a=1&b=2'); // "1"
gup('a', 'http://example.com/page.php?b=2'); // null

关于javascript - 获取 URL 参数函数,获取 url 部分的值,或者如果存在但没有值则返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3054819/

32 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com