首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JavaScript更改用户输入的URL输出

使用JavaScript更改用户输入的URL输出
EN

Stack Overflow用户
提问于 2020-11-12 05:35:15
回答 2查看 26关注 0票数 0

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

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

。。点击"submit",当网址显示为链接时,更改为: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/en-us/替换http://sharepoint.com/,并保留URL的其余部分?

谢谢

编辑:2个很好的答案,谢谢,我将第一个答案改编为我的原始代码,同时我尝试第二个答案,看看它如何比较!:

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-12 05:46:38

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

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

然后你就可以这样做

代码语言:javascript
复制
const updatedUrl = url.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');

然后updatedUrl会得到你想要的东西。

票数 1
EN

Stack Overflow用户

发布于 2020-11-12 05:53:40

It1在我之前就得到了它!无论如何,这是如何直接从输入字段更改它的更高级表示。

代码语言:javascript
复制
<!DOCTYPE html>
    <html>
    <body>
    
    <input id="demo" value="http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com">
    
    <button onclick="myFunction()">Try it</button>
    
    <script>
    function myFunction() {
      var str = document.getElementById("demo").value; 
      var changed = str.replace("sharepoint", "sharepointusa");
      document.getElementById("demo").value = changed;
    }
    </script>
    
    </body>
    </html>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64794472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档