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

如何从输入框提取前两个单词生成无分隔符的URL格式内容

需求与代码修改方案

当前已有两个输入框,原jQuery代码实现了输入business_name时自动生成business_url的功能:将输入内容转为小写,并用连字符替换非字母数字字符(例如输入“My Business Name”会生成“my-business-name”)。现需调整逻辑为:仅提取前两个单词,去除所有分隔符,生成“mybusiness”这类无连接符的小写格式。


现有HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />

原jQuery代码

$(document).ready(function() {
   $("#business_name").keyup(function() {
      var Text = $(this).val();
      Text = Text.toLowerCase();
      Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
      $("#business_url").val(Text);        
    });
});

修改后的jQuery代码

$(document).ready(function() {
   $("#business_name").keyup(function() {
      var Text = $(this).val();
      // 转为小写
      Text = Text.toLowerCase();
      // 按空白分割为单词列表,过滤空内容(处理连续空格)
      const words = Text.split(/\s+/).filter(word => word.trim() !== '');
      let processedText = '';
      // 根据单词数量取前1或2个拼接
      if (words.length >= 2) {
        processedText = words[0] + words[1];
      } else if (words.length === 1) {
        processedText = words[0];
      }
      // 移除所有非字母数字字符
      processedText = processedText.replace(/[^a-zA-Z0-9]/g, '');
      $("#business_url").val(processedText);        
    });
});

逻辑说明

  1. 保留转小写操作,确保输出格式统一
  2. 用正则/\s+/分割内容为单词列表,过滤空项避免连续空格干扰
  3. 按单词数量处理:有2个及以上单词时取前两个直接拼接,只有1个单词时直接使用该单词
  4. 最后移除所有非字母数字字符,保证输出内容合规
  5. 测试示例:
    • 输入My Business Name → 输出mybusiness
    • 输入Big Tech Corp → 输出bigtech
    • 输入Cafe 123 → 输出cafe123

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:35:15