0

I would like to normalise the first name of my users when the type it on an input field.

<input type="text" name="firstName">

So, when the user types:

  • tommy, it should be corrected to Tommy.
  • jean-claude, it should be corrected to Jean-Claude.

Is there a function to do this ?

This is what I tried:

new_str = str.toLowerCase().replace(/\b[a-z]/g, function(txtVal) {
    return txtVal.toUpperCase();
});
$('.list-title').text(new_str);

But it doesn't work for the second case.

Thanks for your help.

Thomas
  • 53
  • 1
  • 7

3 Answers3

1

Using CSS text-transform and regex

REGEX demo

function print() {
  let input = $('input').val().replace(/(?:^|[\s-])\w/g, function(str) {
    return str.toUpperCase()
  })

  console.log(input)
}
input {
  text-transform: capitalize;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="firstName">
<button onclick="print()">print</button>
User863
  • 19,346
  • 2
  • 17
  • 41
0

You can use the on('input',) event listener with jQuery. on('input')

$('.list-title').on('input', function(event) {
    str = $('.list-title').val();
    new_str = str.toLowerCase().replace(/\b[a-z]/g, function(txtVal) {
        return txtVal.toUpperCase();
    });
    $('.list-title').val(new_str);
});

This will automatically run your function anytime the user changes something

bobjoe
  • 673
  • 6
  • 11
0

Add One more step.

var new_str = "Jean-Claude";
new_str = new_str.toLowerCase().replace(/-[a-z]/g,function(txtVal){return txtVal.toUpperCase();});
new_str = new_str.replace(/\b[a-z]/g,function(txtVal){return txtVal.toUpperCase();});
console.log(new_str);
BeiBei ZHU
  • 343
  • 2
  • 12