将 url 中的一个字符串替换为另一个字符串

Replacing a string in url with another string

本文关键字:字符串 一个 替换 另一个 url      更新时间:2023-09-26

用filmot替换imgur,

输入框 - https://i.stack.imgur.com/Uguvn.jpg

"提交"按钮

在新标签页中单击提交后 http://i.filmot.com/abcde.jpg必须打开。

<html>
 <head>
 <title>input</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function myFunction() {
    var res = str1.replace("imgur", "filmot");
    var win = window.open(res, '_blank');
    win.focus();
});
</script>
</head>
<body>
 <form>
 <input type=”text” id=”str1” />
<button onclick="myFunction()">Click</button>
</form>
</body>
</html>

返回代码不起作用。请指教。

谢谢:)

编辑:

下面是解决方案代码:)

<html>
 <head>
 <title>input</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function myFunction() {
  var str1 = document.getElementById('str1').value;
  var res = str1.replace("imgur", "filmot");
  document.getElementById('str1').value = res;
  var win = window.open(res, '_blank');
  win.focus();
}
</script>
</head>
<body>
<input type="text" id="str1" />
<button onclick="myFunction()">Click</button> 
</body>
</html>

试试这个:

<script>
function myFunction() {
   var str1 = document.getElementById('str1').value; // add this
   var res = str1.replace("imgur", "filmot");
   var win = window.open(res, '_blank');
   win.focus();
} // <-----do a proper function closing.
</script>

需要提到的另一件事可能是您使用的引号type=”text” id=”str1”,它们不是正确的引号。这应该改为:

type="text" id="str1"

查看演示:

function myFunction() {
  var str1 = document.getElementById('str1').value;
  var res = str1.replace("imgur", "filmot");
  document.getElementById('str1').value = res;
  //window.open(res, '_blank');
  //win.focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str1" value="http://i.imgur.com/abcde.jpg" />
<button onclick="myFunction()">Click</button>

更改此代码。

var res = str1.replace("imgur", "filmot");

var res = $("#str1").val().replace("imgur", "filmot");

您的代码没有从文本框中获取值......您只是使用了对文本框的引用。

更新

在函数结束时,将});更改为}

参考打开新窗口教程:

要打开一个新窗口,您需要使用另一个现成的 JavaScript 函数。下面是它的样子:

window.open('url to open','window name','attribute1,attribute2')

我已经编辑了函数(添加了窗口名称'),它工作正常,替换了 url a,然后在新选项卡中打开它:

function myFunction() {
  var str1 = document.getElementById('str1').value;
  var res = str1.replace("imgur", "filmot");
  window.open(res, 'new window', '_blank');
} 

这是工作演示

请尝试以下操作:

<html>
 <head>
 <title>input</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function myFunction() {
    var newString=str1.value;
    var res = newString.replace("imgur", "filmot");
    var win = window.open(res, '_blank');
    win.focus();
};
</script>
</head>
<body>
 <form>
 <input type="text" id="str1" value=""/>
<button onclick="myFunction();">Click</button>
</form>
</body>
</html>