Reputation: 908
I'm using the following jQuery to capitalize the 1st letter of an input script.
$('li.capitalize input').keyup(function(event) {
var textBox = event.target;
var start = textBox.selectionStart;
var end = textBox.selectionEnd;
textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1);
textBox.setSelectionRange(start, end);
});
In addition, I now need to capitalize a letter at a specific position (not the first letter) in a string comprising letters and numbers.
For example: Da1234Z I need to capitalize both D and Z.
How can I do this?
Upvotes: 3
Views: 1084
Reputation: 908
Thank you all. I got to capitalize the 7th letter like this:
<script>
jQuery.noConflict();
jQuery(document).ready(function($) {
$('li.capitalize input').keyup(function(event) {
var textBox = event.target;
var start = textBox.selectionStart;
var end = textBox.selectionEnd;
textBox.value = textBox.value.slice(0,7) + textBox.value.charAt(7).toUpperCase() + textBox.value.slice(8);
textBox.setSelectionRange(start, end);
});
});
</script>
Upvotes: 0
Reputation: 1271
You can use this function to capitalize the n-th character of a string:
function capitalizeNth(text, n) {
return (n > 0 ? text.slice(0, n) : '') + text.charAt(n).toUpperCase() + (n < text.length - 1 ? text.slice(n+1) : '')
}
If you know that n can't be negative you can even shorten it to:
function capitalizeNth(text, n) {
return text.slice(0,n) + text.charAt(n).toUpperCase() + text.slice(n+1)
}
Upvotes: 2