I use this (I guess typical) function to make a first letter in a sentece capital:
function firstLetteCap(string) {
return string.charAt(0).toUpperCase() string.slice(1) }
Works perfect till there is an empty variable:
// This works perfect
first = "just"
sentence = `${first} a string`
document.getElementById("p2").innerHTML = `${firstLetteCap(sentence)}.`
// With an empty variable it doesn’t work (capitalized "a" expected)
first = ""
sentence = `${first} a string`
document.getElementById("p3").innerHTML = `${firstLetteCap(sentence)}.`
I would like to know how to fix that, but maybe some context would be also perfect (maybe I don’t get something on how the strings works with variables).
Expected: Just a string.
Thanks!
CodePen: https://codepen.io/vojtacejnek/pen/eYybRqg
CodePudding user response:
Since, first letter of the sentence
variable is
(space).
first = ""
sentence = `${first} a string`
document.getElementById("p3").innerHTML = `${firstLetteCap(sentence)}.`
If you want to ignore the extra spaces, you can use .trim()
.