search - 如何将 & 搜索查询自动转换为 %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
解决方案
您可以在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>
推荐阅读
- javascript - 按钮样式在生产中出现不同
- python - Python函数,在给定输出的情况下求解输入
- javascript - 如何在javascript中将字符串与通配符匹配
- javascript - redux reducer 不更新 store 中的状态
- php - 将一个变量中的两个值插入数据库
- javascript - Javascript 发送图片
- python - pandas dataframe groupby add second level index (integer) based on position in group
- reactjs - 将警告视为错误,因为 process.env.CI = true。编译失败
- python-3.x - wxPython:在 wx.TextEntryDialog 中使用 SetHint
- java - 如何在 mac os 中设置属性 chrome 驱动程序