首页 > 解决方案 > 使用 JavaScript 更改用户输入的 URL 输出

问题描述

我正在尝试在这里构建一些简单的东西:

用户在输入字段中输入 url,例如。http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com

.. 点击“提交”,当 URL 作为链接吐出时,变为:https://sharepointusa.com/en-us/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com

我一直试图吐出整个 URL,丢失参数,但没有成功,所以我需要一种新方法,什么是简单的香草 javascript,只需用https://sharepointusa.com/替换http://sharepoint.com/ en-us/并留下 URL 的其余部分?

谢谢

编辑:2个很好的答案,谢谢,我将第一个答案改编为我的原始代码,而我则在玩第二个答案以查看它的比较!:

<a href="" id="link"></a><br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
  var input=document.getElementById('userInput').value;//gets the value entered by user
const updatedUrl = input.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
    document.getElementById("link").href = updatedUrl;
    document.getElementById("link").innerHTML = updatedUrl;
    

}

</script>

标签: javascripturl

解决方案


如果您有一个包含完整原始网址的变量

const url = 'http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com';

那么你可以做

const updatedUrl = url.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');

和 updatedUrl 将有你所要求的。


推荐阅读