如果您知道page=xxx
參數是已經在那裏,你可以使用.replace()
:
currentPageUrl: req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage)
如果您不知道自己是否是有,那麼你必須首先測試它:
let newUrl;
if (req.originalUrl.indexOf("page=") !== -1) {
newUrl = req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage);
} else if (req.originalUrl.indexOf("?") === -1) {
newUrl = req.originalUrl + "?page=" + currentPage);
} else {
newUrl = req.originalUrl + "&page=" + currentPage);
}
各種測試情況:
function updatePage(origUrl, currentPage) {
let newUrl;
if (origUrl.indexOf("page=") !== -1) {
newUrl = origUrl.replace(/page=[^&]+/, "page=" + currentPage);
} else if (origUrl.indexOf("?") === -1) {
newUrl = origUrl + "?page=" + currentPage;
} else {
newUrl = origUrl + "&page=" + currentPage;
}
return newUrl;
}
// test cases
console.log(updatePage("http://somedomain.com/somePath?page=3", 5));
console.log(updatePage("http://somedomain.com/somePath?whatever=something&page=3", 5));
console.log(updatePage("http://somedomain.com/somePath", 5));
console.log(updatePage("http://somedomain.com/somePath?page=3&whatever=something", 5));
您也可以使用url
庫的URL解析成其組成部分,改變其中的一部分,然後重新生成完整的URL:
const url = require('url');
let parsedUrl = url.parse(req.originalUrl, true);
parsedUrl.query.page = currentPage;
delete parsedUrl.search;
let newUrl = url.format(parsedUrl);
什麼,我覺得這個工作正常在我的情況。謝謝你幫忙! – Codearts