Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim input field value to only alphanumeric characters/separate spaces with . with jQuery

So I'm trying to have an input field where I can enter any characters, but then take the inputted value lowercase it, remove any non alphanumeric characters, leaving "." instead of spaces.

For example, If I enter:
Earth is 70% water, -!*#$^^ & 30% LAnd

The output should be:
earth.is.70.water.30.land

Any idea how this can be done without masking with jQuery?

like image 257
Maverick Avatar asked Dec 12 '22 11:12

Maverick


1 Answers

This is not really a jQuery question, it can be done with simple Javascript. First you need to lowercase the text, then replace spaces with periods, then remove non-alphanumeric:

var myStr = "Earth is 70% water, -!*#$^^ & 30% LAnd"
myStr=myStr.toLowerCase();
myStr=myStr.replace(/ /g,".");
myStr=myStr.replace(/[^a-zA-Z0-9\.]+/g,"");

This answer would leave multiple spaces as periods, as the user inputted. If you want it to match your answer (which actually condenses multiple spaces into one), then add on an extra replace:

myStr=myStr.replace(/\.+/g, ".");
like image 51
T Nguyen Avatar answered May 12 '23 06:05

T Nguyen