javascript - Javascript - 如何编写带有参数的条件window.location.href

我有以下javascript代码行用于网页重定向。


<script>


 window.location.href ="https://www.example.com/example_0/" + document.location.search;


</script>



让我来解释一下,原始的网址是这样的:


http://www.example.com/result.php?clientId=528873&lang=IT



我必须确保在URL中读取了clientId =参数,并基于此参数将用户通过此正确的window.location.href命令重定向到正确的URL,例如,如果clientID为= 849679,则返回以下内容:


window.location.href ="https://www.example1.com/example_1/" + document.location.search;



而如果参数为818586,它将通过此命令将用户重定向到正确的网址,


window.location.href ="https://www.example2.com/example_2/" + document.location.search;



谁能帮我写正确的代码?

时间:

你可以使用urlSearchParams,具体取决于你的浏览器支持,https://caniuse.com/#feat=urlsearchparams


const urlParams = new URLSearchParams(window.location.search);


const clientId = urlParams.get('clientId');



if(clientId === '849679') {


 window.location.href ="https://www.example1.com/example_1/" + document.location.search;


} else if (clientId === '818586') {


 window.location.href ="https://www.example2.com/example_2/" + document.location.search;


}

另一种解决方案是使用regexp或库提取查询参数。


function getParameterByName(name) {


 var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);


 return match && decodeURIComponent(match[1].replace(/+/g, ' '));


}



const clientId = getParameterByName('clientId');



if(clientId === '849679') {


 window.location.href ="https://www.example1.com/example_1/" + document.location.search;


} else if (clientId === '818586') {


 window.location.href ="https://www.example2.com/example_2/" + document.location.search;


}

...