Reputation: 129
I am using the following jQuery to allow a user to enter some text into a text field which is then rendered elsewhere on the screen within a div.
I am able to get the text to render in uppercase and lowercase but I'm not too sure how to get it to render in title case, or a mixture of both cases.
This is the code:
jQuery('#fhc-sloganText').keyup(function() {
var plateSlogan = document.getElementById("plateSlogan");
plateSlogan.innerHTML = this.value.toLowerCase();
});
I believe I need to be using RegExp but I'm finding it difficult trying to implement it into this scenario.
Upvotes: 1
Views: 1419
Reputation: 89412
You can use this function to capitalize each word in a String.
function toTitleCase(str){
return str.replace(/\b\w/g, l => l.toUpperCase());
}
#plateSlogan{
height: 50px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fhc-sloganText"/>
<p/>
<div id="plateSlogan"></div>
<script>
jQuery('#fhc-sloganText').keyup(function() {
var plateSlogan = document.getElementById("plateSlogan");
plateSlogan.innerHTML = this.value.replace(/\b\w/g, l => l.toUpperCase());
});
</script>
You can use this function to capitalize the first word in a String>
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + string.slice(1);
}
#plateSlogan{
height: 50px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fhc-sloganText"/>
<p/>
<div id="plateSlogan"></div>
<script>
jQuery('#fhc-sloganText').keyup(function() {
var plateSlogan = document.getElementById("plateSlogan");
plateSlogan.innerHTML = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
</script>
Upvotes: 2