You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现输入文本复制到第二个搜索框时自动去除文本之间的空格

实现可行性说明

这个需求完全可以实现,实现难度极低,仅需要对你现有代码做少量调整即可。

实现思路

你目前所有目标搜索框共用同一个copied-content类,所以只需要给需要去除空格的第二个搜索框新增一个专属标识类,在同步赋值时根据标识做不同的处理即可:

  • 普通目标搜索框直接赋值主输入框的原始内容
  • 带专属标识的搜索框,先把主输入框内容的所有空格删除后再赋值

修改后的代码示例

HTML修改部分

给第二个Instagram搜索框的input新增no-space标识类:

<form action="https://www.instagram.com/explore/tags/" target="_blank" data-searchmethod="getParameters">
  <input class="copied-content no-space" type="text" name="q">
  <button>Search Instagram</button>
</form>

JS修改部分

调整遍历赋值的逻辑,判断元素是否携带no-space类,对应做空格处理:

const otherSearchBars = document.querySelectorAll('.copied-content');
// 改用id选择主搜索框,避免页面存在其他input时逻辑出错
document.querySelector('#searchinput').addEventListener('input', function() {
  const inputVal = this.value;
  otherSearchBars.forEach(el => {
    if (el.classList.contains('no-space')) {
      // 移除所有空格后赋值
      el.value = inputVal.replace(/\s/g, '');
    } else {
      // 直接赋值原始内容
      el.value = inputVal;
    }
  })
})

内容的提问来源于stack exchange,提问作者HelloWorld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 06:39:02