jquery - 动态生成url
我试图在用户输入内容时动态创建一个 url slug。应删除不需要的字符。空格应替换为连字符,并将所有内容替换为小写。因此,如果用户输入“Ruddy's Cheese Shop”,它应该呈现“ruddys-cheese-shop”。
这是我到目前为止所拥有的。
<input id="tb1" />
<div id="tb2"></div>
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$('#tb2').html($('#tb1').val(Text));
});
它几乎可以工作,但我是 js 新手。谢谢
I am trying to dynamically create a url slug when a user types into an input. Unwanted characters should be removed. Spaces should be replaced by hyphens and everything into lowercase. So if a user types "Ruddy's Cheese Shop" it should render "ruddys-cheese-shop".
This is what I have so far.
<input id="tb1" />
<div id="tb2"></div>
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$('#tb2').html($('#tb1').val(Text));
});
It almost works but I am new to js. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的代码但略有改进。
您不需要一遍又一遍地查找
$('#tb1')
元素,因为您在函数内部将其引用为$(this)
。http://jsfiddle.net/jFjR3/
Your code but slightly improved.
You don't need to find
$('#tb1')
element over and over again since you have a refference to it inside the function as$(this)
.http://jsfiddle.net/jFjR3/
除了您设置 #tb2 值的位置之外,它看起来不错。我想你想要:
当然,请记住,既然你调用了 toLowerCase,你就不需要替换大写字符。相反,更简单的正则表达式:
如果您还想在用户键入时更新编辑字段,这里有一个完整的示例。请注意,它只会在您开始输入时更新#td2。
It looks ok except where you set the #tb2 value. I think you want:
Of course, remember since you've called toLowerCase, you don't need to replace upper case chars. Rather a simpler regexp:
If you also want to update the edit field as the user types, here's a full example. Note that it will only update #td2 when you start typing.
看起来您需要运行一些替换,
即将 ruddy's Cheese Shop 转换为 ruddys-cheese-shop
希望有帮助
Looks like you need to run a couple of replaces i.e.
That converts ruddy's Cheese Shop to ruddys-cheese-shop
Hope that helps