MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / titleCaseConversion

Function titleCaseConversion

Conversions/TitleCaseConversion.js:13–47  ·  view source on GitHub ↗
(inputString)

Source from the content-addressed store, hash-verified

11 * @returns {string} A string that is in title case.
12 */
13const titleCaseConversion = (inputString) => {
14 if (inputString === '') return ''
15 // Extract all space separated string.
16 const stringCollections = inputString.split(' ').map((word) => {
17 let firstChar = ''
18 // Get the [ASCII](https://en.wikipedia.org/wiki/ASCII) character code by the use charCodeAt method.
19 const firstCharCode = word[0].charCodeAt()
20 // If the ASCII character code lies between 97 to 122 it means they are in the lowercase so convert it.
21 if (firstCharCode >= 97 && firstCharCode <= 122) {
22 // Convert the case by use of the above explanation.
23 firstChar += String.fromCharCode(firstCharCode - 32)
24 } else {
25 // Else store the characters without any modification.
26 firstChar += word[0]
27 }
28 const newWordChar = word
29 .slice(1)
30 .split('')
31 .map((char) => {
32 // Get the ASCII character code by the use charCodeAt method.
33 const presentCharCode = char.charCodeAt()
34 // If the ASCII character code lies between 65 to 90, it means they are in the uppercase so convert it.
35 if (presentCharCode >= 65 && presentCharCode <= 90) {
36 // Convert the case by use of the above explanation.
37 return String.fromCharCode(presentCharCode + 32)
38 }
39 // Else return the characters without any modification.
40 return char
41 })
42 // Return the first converted character and remaining character string.
43 return firstChar + newWordChar.join('')
44 })
45 // Convert all words in a string and return it.
46 return stringCollections.join(' ')
47}
48
49export { titleCaseConversion }

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected