Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip spaces and make string lowercase with Javascript [duplicate]

I have the following script that duplicates the content I'm entering in one field into another.

DEMO: https://jsfiddle.net/wk3nmc76/

I was wondering if it's possible I could change the 2nd field to strip spaces & make the value lowercase?

<p><input type="text" name="full_name" id="full_name" placeholder="Full Name"/></p>
<p><input type="text" name="last_name" id="last_name"></p>
$('#full_name').keyup(function(){
   $('#last_name').val(this.value);
});
like image 734
michaelmcgurk Avatar asked Aug 27 '26 02:08

michaelmcgurk


1 Answers

To achieve this you can use a combination of toLowerCase() and a regular expression to remove all the spaces. Try this:

$('#full_name').on('input', e => {
  $('#last_name').val(e.target.value.toLowerCase().replace(/\s/g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<p>
  <input type="text" name="full_name" id="full_name" placeholder="Full Name" />
</p>

<p>
  <input type="text" name="last_name" id="last_name">
</p>

2023 Update

The replaceAll() method now has broad enough browser support for it to be a viable alternative to using a Regular Expression:

$('#full_name').on('input', e => {
  $('#last_name').val(e.target.value.toLowerCase().replaceAll(' ', ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<p>
  <input type="text" name="full_name" id="full_name" placeholder="Full Name" />
</p>

<p>
  <input type="text" name="last_name" id="last_name">
</p>
like image 103
Rory McCrossan Avatar answered Aug 28 '26 15:08

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!