I've successfully followed the steps outlined at Convert string to Title Case with JavaScript however was wondering if there as a way for me to ensure certain words remain lowercase?
For example "THE university Of Maastricht" should become "The University of Maastricht" and "The queen Of The nile" should become "The Queen of the Nile".
This would mean excluding words which match "of" and "the" (in any capitalisation combination) except if they are the first word?
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( /\w\S*/g, function(txt) { console.log(txt, str.indexOf(txt).== 0 && lowerCaseList.includes(txt.toLowerCase())) 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 is extend from this answer .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.