See if there are input spaces with jQuery

I am trying to write a function that reads the value of the input data and determines if the space was used during creation. I'm not trying to trim anything - just see if he needs the ability to trim.

I donโ€™t even know where to start, so I donโ€™t have any code to view. Please help if you can!

I tried this solution, but it does not work (I do not think I am using .has () correctly)

if ($('#id').val().has(" ")) { alert('has spaces') } 
+4
source share
2 answers

Use val and indexOf :

 var hasSpace = $('#myInputId').val().indexOf(' ')>=0; 

If you want to test other types of spaces (for example, tabs), you can use the regex:

 var hasSpace = /\s/g.test($('#myInputId').val()); 

Demonstration

+15
source

Usage contains for include space:

 var value = $('#myInputId').val(); if(value.contains(' ')){ console.log("has space"); } 

Or you can find with these ascII code & nbsp and \ xA0

 if(value.contains(' ')){ console.log("has space"); } 
0
source

Source: https://habr.com/ru/post/1444425/


All Articles