[Solved] Javascript convert string to sentence case with certain exclusions [duplicate]


You can check if the indexOf the txt not 0 so it’s not first word, and create a list of excluded words and also check if this list includes the txt, then return the txt as it is.

const lowerCaseList = ["of", "and"]

function toTitleCase(str) {
  return str.replace(
    /\p{L}+/gu,
    function(txt) {
      if (str.indexOf(txt) !== 0 && lowerCaseList.includes(txt.toLowerCase())) {
        return txt.toLowerCase();
      }
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}
<form>
  Input:
  <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
  <br />Output:
  <br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

This answer extends from this answer.

9

solved Javascript convert string to sentence case with certain exclusions [duplicate]