【问题标题】:How to replace part of url with the value from an input box如何用输入框中的值替换部分url
【发布时间】:2022-12-08 21:52:35
【问题描述】:

我希望用我在输入搜索栏中输入的值替换 URL 的一部分。

这是我已经获取的当前 URL:

const url = "https://newsapi.org/v2/top-headlinescountry=us&q=&apiKey=[API-key]"

function searchFunction() {
    let searchBar = document.getElementById("searchBar");
      searchBar.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            let searchBarValue = searchBar.value;
            url = `https://newsapi.org/v2/top-headlines?country=us&q={searchBarValue}&apiKey=[API-key]`
          }
    });
  }
  searchFunction();

【问题讨论】:

  • &q={searchBarValue} 更改为 &q=${searchBarValue}
  • 谢谢,但它不起作用...
  • 你正在改变变量,你期待的不仅仅是变量的改变吗?
  • 我想在按回车键时用我输入到输入框中的文本替换字符串的一部分

标签: javascript input


【解决方案1】:

你可以做:

const url = 'https://newsapi.org/v2/top-headlinescountry=us&q=&apiKey=%5BAPI-key%5D'

const searchFunction = () => {
  const searchBar = document.getElementById('searchBar')
  searchBar.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      let searchBarValue = searchBar.value
      url = url.replace('&q=', `&q=${searchBarValue}`)
    }
  })
}
searchFunction()

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 2022-11-23
    • 2012-01-29
    • 1970-01-01
    • 2018-12-21
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多