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?
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?
3 Answers
Reset to default 7Instead 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/ue1vedez/
How about to add another replace()
which would remove the ending dash
str = str.replace(/\W+/g, '-').replace(/\-$/, '').toLowerCase();
$('#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);
});
Use W+ instead just W, because it so not allow put '-' in last when type various characters into last