首页 > 解决方案 > 如何将 & 搜索查询自动转换为 %26

问题描述

我构建了一个简单的表单,将用户创建的输入查询发送到https://www.google.com/search?q=

一切都很好,除了用户在搜索中输入 & 时。因此,例如,如果用户在搜索表单中输入的是 Anderson, Johnson, & Smith Associates,则查询会在之后中断,Anderson, Johnson因为 Google 无法识别&.

是否有脚本或我可以添加到“提交”按钮的内容,以便如果用户查询包含 &,它会自动将其转换为%26. 因此,例如,如果用户输入Anderson, Johnson, & Smith Associates表单,则发送给 Google 的相应查询是: https://www.google.com/search?q=Anderson,%20Johnson,%20%26%20Smith%20Associates

标签: searchgoogle-search

解决方案


您可以在encodeURIComponent()将字符串添加到 URL 之前使用它来解析字符串,即:

var url = 'https://www.google.com/search?q=' + encodeURIComponent(<YourStringHere>);

这是一个概念验证示例:

document.querySelector('#button').addEventListener('click', function() {
  var query = document.querySelector('#query').value;
  var url = 'https://www.google.com/search?q=' + encodeURIComponent(query);

  console.log(url);
  const link = document.querySelector('#link');
  link.href = url;
  link.innerHTML = url;
});
a {
  display: block;
}
<input type="text" id="query" value="Anderson, Johnson, & Smith Associates" />
<button type="button" id="button">Search on Google</button>

<a href="#" id="link"  target="_blank"></a>


推荐阅读