问题:
您需要修改 'rows' URL 参数在给定 URL 中添加特定值,如果没有,则添加默认值
解决方案:
使用 updateURLParameter 等 JavaScript 函数来操作 URL 参数。以下是问题答案中提供的代码的扩展版本:
/** * http://stackoverflow.com/a/10997390/11236 */ function updateURLParameter(url, param, paramVal) { let newAdditionalURL = ""; const tempArray = url.split("?"); const baseURL = tempArray[0]; let additionalURL = tempArray[1]; let temp = ""; if (additionalURL) { const additionalURLArray = additionalURL.split("&"); additionalURLArray.forEach((paramValue) => { if (paramValue.split('=')[0] != param) { newAdditionalURL += temp + paramValue; temp = "&"; } }); } const rows_txt = temp + "" + param + "=" + paramVal; return baseURL + "?" + newAdditionalURL + rows_txt; } // Function Calls: const newURL1 = updateURLParameter(window.location.href, 'locId', 'newLoc'); const newURL2 = updateURLParameter(newURL1, 'resId', 'newResId'); window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
更新版本处理 URL 锚点:
function updateURLParameter(url, param, paramVal) { let TheAnchor = null; let newAdditionalURL = ""; const tempArray = url.split("?"); const baseURL = tempArray[0]; let additionalURL = tempArray[1]; let temp = ""; if (additionalURL) { const tmpAnchor = additionalURL.split("#"); TheParams = tmpAnchor[0]; TheAnchor = tmpAnchor[1]; if (TheAnchor) additionalURL = TheParams; const tempArray = additionalURL.split("&"); tempArray.forEach((paramValue) => { if (paramValue.split('=')[0] != param) { newAdditionalURL += temp + paramValue; temp = "&"; } }); } else { const tmpAnchor = baseURL.split("#"); TheParams = tmpAnchor[0]; TheAnchor = tmpAnchor[1]; if (TheParams) baseURL = TheParams; } if (TheAnchor) paramVal += "#" + TheAnchor; const rows_txt = temp + "" + param + "=" + paramVal; return baseURL + "?" + newAdditionalURL + rows_txt; }
以上是如何使用 JavaScript 修改 URL 参数并指定默认值?的详细内容。更多信息请关注PHP中文网其他相关文章!