如何从输入框提取前两个单词生成无分隔符的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); }); });
逻辑说明
- 保留转小写操作,确保输出格式统一
- 用正则
/\s+/分割内容为单词列表,过滤空项避免连续空格干扰 - 按单词数量处理:有2个及以上单词时取前两个直接拼接,只有1个单词时直接使用该单词
- 最后移除所有非字母数字字符,保证输出内容合规
- 测试示例:
- 输入
My Business Name→ 输出mybusiness - 输入
Big Tech Corp→ 输出bigtech - 输入
Cafe 123→ 输出cafe123
- 输入
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

