forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTitleCaseConversion.js
More file actions
Latest commit
49 lines (47 loc) · 2.25 KB
/
Copy pathTitleCaseConversion.js
File metadata and controls
49 lines (47 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Problem statement and Explanation : https://www.codeproject.com/Tips/162540/Letter-Case-Conversion-Algorithms-Title-Case-Toggl.
[Title case](https://en.wikipedia.org/wiki/Title_case) is a style where all words are capitalized. Officially, title case
does not capitalize some words, such as very short words like "a" or "is", but for the purposes of this function, a general approach
is taken where all words are capitalized regardless of length.
*/
/**
* The titleCaseConversion function converts a string into a title case string.
* @param {string} inputString The input string which can have any types of letter casing.
* @returns {string} A string that is in title case.
*/
consttitleCaseConversion=(inputString)=>{
if(inputString==='')return''
// Extract all space separated string.
conststringCollections=inputString.split(' ').map((word)=>{
letfirstChar=''
// Get the [ASCII](https://en.wikipedia.org/wiki/ASCII) character code by the use charCodeAt method.
constfirstCharCode=word[0].charCodeAt()
// If the ASCII character code lies between 97 to 122 it means they are in the lowercase so convert it.
if(firstCharCode>=97&&firstCharCode<=122){
// Convert the case by use of the above explanation.
firstChar+=String.fromCharCode(firstCharCode-32)
}else{
// Else store the characters without any modification.
firstChar+=word[0]
}
constnewWordChar=word
.slice(1)
.split('')
.map((char)=>{
// Get the ASCII character code by the use charCodeAt method.
constpresentCharCode=char.charCodeAt()
// If the ASCII character code lies between 65 to 90, it means they are in the uppercase so convert it.
if(presentCharCode>=65&&presentCharCode<=90){
// Convert the case by use of the above explanation.
returnString.fromCharCode(presentCharCode+32)
}
// Else return the characters without any modification.
returnchar
})
// Return the first converted character and remaining character string.
returnfirstChar+newWordChar.join('')
})
// Convert all words in a string and return it.
returnstringCollections.join(' ')
}
export{titleCaseConversion}