Richy Richy - 1 year ago 45
Javascript Question

Keep all alpha and numeric characters and turn white space into -

What im trying to do is:
Take a string

  1. remove anything that is not alpha and numeric characters.

  2. Im also trying to turn any white space into a -, (multiple white space will become a single -)

  3. covert all into lower case

The reason for this is to generate a friendly URL from a user input

This is all i have so far

var str = "This is a really bad Url _, *7% !";
result1 = str.replace(/\s+/g, '-').toLowerCase();

Answer Source

This could do the trick

var str = "This is    a really bad Url _, *7% !";
result1 = str.replace(/[^a-zA-Z0-9\s]/g, '') // Remove non alphanum except whitespace
             .replace(/^\s+|\s+$/, '')      // Remove leading and trailing whitespace
             .replace(/\s+/g, '-')          // Replace (multiple) whitespaces with a dash

Result :