我正在尝试在用户输入输入时动态创建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的新手。感谢
答案 0 :(得分:1)
您的代码但略有改进。
$('#tb1').keyup(function() {
var text = $(this).val().toLowerCase();
text = text.replace(/[^a-z0-9]+/g, '-');
$('#tb2').text(text);
});
您不需要一遍又一遍地找到$('#tb1')
元素,因为您在函数内部对$(this)
进行了参考。
答案 1 :(得分:0)
除非您设置#tb2值,否则它看起来不错。我想你想要:
$('#tb2').html(Text);
当然,请记住,因为你已经调用了toLowerCase,所以你不需要替换大写字符。而是一个更简单的正则表达式:
Text = Text.replace(/[^a-z0-9]+/g,'-');
如果您还想在用户输入时更新编辑字段,这是一个完整的示例。请注意,它只会在您开始输入时更新#td2。
<html>
<head>
<script src="js/jquery.js" ></script>
<script language="javascript">
$(function() {
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-z0-9]+/g,'-');
$('#tb2').html(Text);
$('#tb1').val(Text);
});
});
</script>
</head>
<body>
<input type="text" id="tb1" value="Ruddy's Cheese Shop" />
<div id="tb2"></div>
</body>
</html>
答案 2 :(得分:0)
看起来你需要进行一些替换,例如
Text = Text.replace(/[\s]+/g,'-');
Text = Text.replace(/[^a-z_0-9\-]+/g,'');
将红润的芝士店改为ruddys-cheese-shop
希望有所帮助