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();

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.

javascript jquery keyup html 

Nov 17

1 Answers

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. 


$('#input_title').on('keyup', function (e) {   
   //console.log("key up");
   var str = $(this).val();
   str = str.replace(/\W+(?!$)/g, '-').toLowerCase();
   str = str.replace(/\W$/, '').toLowerCase();

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

answered Dec 02

Login and Submit Your Answer
Browse other questions tagged  javascript  jquery  keyup  html or ask your own question.