Convert to Uppercase
toUpperCase() method. This method will create a new string from the original string which we can store in a variable.
var string = 'this is some text'; var result = string.toUpperCase(); console.log(result);
THIS IS SOME TEXT
Convert to Lowercase
To convert all characters to uppercase use the
toLowerCase() method. Like to
toLowerCase() will return a new string that could be used immediately or stored in a variable for later use.
var string = 'tHis iS sOme tExt'; var result = string.toLowerCase(); console.log(result);
this is some text
Make the First Character Uppercase
Like many other programming languages, a string is an iterable with each element having an index, the first element is at index
0. With that in mind, to change the first character to uppercase we just have to modify the first index of the string and replace it with an uppercase character. There are a number of ways to approach this but the probably the easiest is by using the
slice() methods and combining the result.
var string = 'this is some text'; var result = string.charAt(0).toUpperCase() + string.slice(1);; console.log(result);
This is some text
Convert a Substring to Uppercase or Lowercase
replace() method and changing the case of the matches before they are added back into the string.
var string = 'this is some text'; var result = string.replace('some', r => r.toUpperCase()); console.log(result);
this is SOME text
In the above example, we are looking for the substring “some” and capitalising it. This is a basic example, which could be expanded on with more elaborate regular expressions for dynamic substring matching.