Question:
I have the function, and it works perfectly:
$.fn.capitalize = function() {
function isTRChar(key) {
var trchar = [231, 246, 252, 287, 305, 351];
for (var i = 0; i < trchar.length; i++) {
if (trchar[i] == key) return true;
}
return false;
}
$.each(this, function() {
var $this = $(this);
if ($this.is('textarea') || $this.is('input:text')) {
$this.on({
keypress: function(event) {
var pressedKey = event.charCode == undefined ? event.keyCode : event.charCode;
var str = String.fromCharCode(pressedKey);
if (pressedKey == 0) {
if (!isTRChar(pressedKey)) return;
}
this.value = this.value.replace(/\b[a-z]/gi, function($0) {
return $0.toUpperCase();
});
this.value = this.value.replace(/@([a-z])[\w\.]*\b/gi, function($0, $1) {
return $0.substring(0, 2).toUpperCase() + $0.substring(2).toLowerCase();
});
if (!this.createTextRange) {
var startpos = this.selectionStart;
var endpos = this.selectionEnd;
if (!$(this).attr('maxlength') ||
this.value.length - (endpos - startpos) < $(this).attr('maxlength')) {
this.setSelectionRange(startpos + 1, startpos + 1);
}
}
}
});
}
});
}
But it doesn't work with accents , cedilla and in proper names, the de or do are also capitalized.
Examples: (how it looks when typed)
Maria Fatima
Jose Gonçalves
How to fix this in this function?
Answer:
hello you can try this [edit]: sorry i hadn't even checked back just now.
function contains(str, search){
if(str.indexOf(search) >= 0){
return true;
} else {
return false;
}
}
$.fn.capitalize = function(str) {
$.each(this, function() {
var split = this.value.split(' ');
for (var i = 0, len = split.length; i < len; i++) {
var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
if (verify == false) {
if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
//alert(split[i]);
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
}
}
this.value = split.join(' ');
});
return this;
};
$("textarea").keypress(function(e) {
var str = String.fromCharCode(e.which);
$(this).capitalize(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<textarea></textarea>