user2770714
user2770714

Reputation: 129

How to output title case text into html field using jquery

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

Answers (2)

Unmitigated
Unmitigated

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

Mojtaba
Mojtaba

Reputation: 5002

You can achieve this goal much easier. Use CSS: plateSlogan.style.textTransform = "capitalize";

Or, if you are using jQuery, you can use the function .css

Upvotes: 2

Related Questions