Regex replace dash space in jQuery

I have the following code that fills a field when entering into another ...

$('#title').bind('keyup keypress blur', function() { var myStr = $(this).val() myStr=myStr.toLowerCase(); myStr=myStr.replace(/ /g,"-"); myStr=myStr.replace(/[^a-zA-Z0-9\.]+/g,""); myStr=myStr.replace(/\.+/g, "-"); $('#filename').val(myStr); }); 

Removing any alphanumeric characters in the code works, however I want them to replace the spaces with the "-" character.

If I change the dash to the period '.' it works, don’t know why and how to fix it? Regex bothers me.

JSFIDDLE here

Can someone point me in the right direction?

UPDATE

It just worked as required, using this ...

 <script> $('#title').bind('keyup keypress blur', function() { var myStr = $(this).val() myStr=myStr.toLowerCase(); myStr=myStr.replace(/[^a-zA-Z0-9 ]+/g,""); myStr=myStr.replace(/\s+/g, "-"); $('#filename').val(myStr); }); </script> 
+6
source share
3 answers

I recommend using this regular expression instead of the first, you have /(^\s+|[^a-zA-Z0-9 ]+|\s+$)/g . This will prevent the addition of dashes at the beginning and end of the line, in case the user accidentally adds spaces.

 $('#title').bind('keyup keypress blur', function() { var myStr = $(this).val() myStr=myStr.toLowerCase(); myStr=myStr.replace(/(^\s+|[^a-zA-Z0-9 ]+|\s+$)/g,""); //this one myStr=myStr.replace(/\s+/g, "-"); $('#filename').val(myStr); }); 

jsfiddle

+5
source

\s means whitespace (\n, \r, \t, \f, and " ") in the regular expression:

 myStr=myStr.replace(/\s+/g, "-"); 
+8
source

You are breaking your own work:

 myStr=myStr.replace(/[^a-zA-Z0-9\.]+/g,""); //removes dashes (-) 

Change it like this:

 myStr=myStr.replace(/[^a-zA-Z0-9\.-]+/g,""); 

You say you want to delete everything that is not a letter, number, or . (therefore removes the dash)

Just adding a dash / hyphen to a character group sorts it

+3
source

All Articles