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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With