Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing special characters with dashes

The user enters their text in #title and JQuery converts the string and places it in an input field named #url. The following code works:

$('#title').on('keyup', function (e) {            
   e.preventDefault();
   var str = $(this).val();
   str = str.replace(/\W+/g, '-').toLowerCase();
   $('#url').val(str);
});

But here is the issue, If i enter Big "Fish" Little "Fish" JQuery will convert this to: big-fish-little-fish-. So the question is how do i remove the last - at the end. Could i use something like before() and then it will do the replacement?

like image 473
Sickaaron Avatar asked Oct 21 '25 05:10

Sickaaron


1 Answers

Instead of doing something to replace the final - you could also use a negative lookahead to avoid replacing anything that occurs at the end of the string and then use a subsequent statement to replace any non word char that occurs at the end with an empty space.

$('#title').on('keyup', function (e) {   
   //alert("key up");
   e.preventDefault();
   var str = $(this).val();
   str = str.replace(/\W+(?!$)/g, '-').toLowerCase();
   str = str.replace(/\W$/, '').toLowerCase();
   $('#url').val(str);
});

Example Fiddle: https://jsfiddle.net/ue1vedez/

like image 171
stephen.vakil Avatar answered Oct 23 '25 17:10

stephen.vakil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!