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

有帮助吗?

解决方案

Your code but slightly improved.

$('#tb1').keyup(function() {
    var text = $(this).val().toLowerCase();
    text = text.replace(/[^a-z0-9]+/g, '-');
    $('#tb2').text(text);
});

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/

其他提示

It looks ok except where you set the #tb2 value. I think you want:

$('#tb2').html(Text);

Of course, remember since you've called toLowerCase, you don't need to replace upper case chars. Rather a simpler regexp:

Text = Text.replace(/[^a-z0-9]+/g,'-');

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.

  <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>

Looks like you need to run a couple of replaces i.e.

Text = Text.replace(/[\s]+/g,'-'); 
Text = Text.replace(/[^a-z_0-9\-]+/g,'');

That converts ruddy's Cheese Shop to ruddys-cheese-shop

Hope that helps

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top