Asked : Nov 17
Viewed : 103 times
I want to beautify my blog url like a WordPress website.
The user enters their text in the input box with id #input_title
and JQuery or JavaScript converts the string and places it in an input field named #title_url
. The following code works using jquery.
$('#input_title').on('keyup', function (e) {
var string = $(this).val();
string = string.replace(/\W+/g, '-').toLowerCase();
$('#title_url').val(string);
});
But here is the issue, If I enter in input box ex, Lorem Ipsum "is" simply dummy "text"
JQuery will convert this to: Lorem-Ipsum-is-simply-dummy-text-
. So the question is how do I can remove the last dash (-) at the end?
Thank you in advance.
Nov 17
alternatively, to replace the final, you should use a negative look ahead to avoid anything that occurs at the end of the string and then use a following statement to replace any special char (non-word) that occurs at the end with an empty space.
Solution:
$('#input_title').on('keyup', function (e) {
//console.log("key up");
e.preventDefault();
var str = $(this).val();
str = str.replace(/\W+(?!$)/g, '-').toLowerCase();
str = str.replace(/\W$/, '').toLowerCase();
$('#title_url').val(str);
});
Example Fiddle: https://jsfiddle.net/ue1vedez/
answered Dec 02