Mark Mark - 6 months ago 29
HTML Question

How to remove white space and special characters using jquery

I have a form with an input field.
I show the value of the field on the page.

$(document).ready(function() {
$('#company').change(function(){
$('#compname').html($('#company').val());
});
});


I need to strip all white space and any special characters entered into the field. (So only alpha/numeric characters are shown and without spaces).

Answer

You could use the following regex /[^A-Z0-9]/ig to do this :

var company_name = $('#company').val().replace(/[^A-Z0-9]/ig, "");
$('#compname').html(company_name);

[^A-Z0-9] : match a single character not present in the list below

A-Z : a single character in the range between A and Z (case insensitive)

0-9 : a single character in the range between 0 and 9

g : modifier: global. All matches (don't return on first match)

i : modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

NOTE : better to use input event to track user change inside an input.

Hope this helps.


$(document).ready(function() {
  $('#company').on('input', function(){
    var company_name = $('#company').val().replace(/[^A-Z0-9]/ig, "");
    $('#compname').html(company_name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="company" placeholder='Company name'/>

<br><br>
Result : <span id="compname"></span>

Comments