How to use every word even after hyphens using jQuery?

I want to use all the words in the input (using the keyup function) to format the entered names.

Examples

:

john doe => John Doe

JOHN DOE => John Doe

tommy-lee => Tommy Lee

I am currently using this code:

$("input").keyup(function() { var cp_value= ucwords($(this).val(),true) ; $(this).val(cp_value ); }); function ucwords(str,force){ str=force ? str.toLowerCase() : str; return str.replace(/(\b)([a-zA-Z])/g, function(firstLetter){ return firstLetter.toUpperCase(); }); } 

But if the word contains an underlined character, it also has a capital letter: John Döe => John DöE.

What is the best solution to get what I want?

thanks

+6
source share
3 answers

Problem with the word border, if you are doing a manual border, it works

 function ucwords(str,force){ str=force ? str.toLowerCase() : str; return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(firstLetter){ return firstLetter.toUpperCase(); }); } 

and adding Unicode for accented characters as well

+6
source

Use this:

 function ucwords(input) { var words = input.split(/(\s|-)+/), output = []; for (var i = 0, len = words.length; i < len; i += 1) { output.push(words[i][0].toUpperCase() + words[i].toLowerCase().substr(1)); } return output.join(''); } 

Testing:

 console.log(ucwords('JOHN DOE'), ucwords('tommy-lee'), ucwords('TOMMY-lee'), ucwords('John Döe')); 
+3
source

you can do something like this after breaking the keyboard, then get fisrt char and smooth it out and then connect everything. you can check this link, I wrote you a demo http://jsfiddle.net/vbx3x/5/

 function ucwords(str,force){ str=force ? str.toLowerCase() : str; var temp= str.split(/(\s|-)+/); for(var i=0; i<temp.length; i++) { temp[i] = temp[i].substr(0,1).toUpperCase() + temp[i].substr(1,temp[i].length-1) } return temp.join(' '); } 
0
source

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


All Articles