Convert JavaScript String to be all lower case

Viewed 517278

How can I convert a JavaScript string value to be in all lower case letters?

Example: "Your Name" to "your name"

15 Answers
var lowerCaseName = "Your Name".toLowerCase();

Use either toLowerCase or toLocaleLowerCase methods of the String object. The difference is that toLocaleLowerCase will take current locale of the user/host into account. As per § 15.5.4.17 of the ECMAScript Language Specification (ECMA-262), toLocaleLowerCase

…works exactly the same as toLowerCase except that its result is intended to yield the correct result for the host environment’s current locale, rather than a locale-independent result. There will only be a difference in the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.

Example:

var lower = 'Your Name'.toLowerCase();

Also note that the toLowerCase and toLocaleLowerCase functions are implemented to work generically on any value type. Therefore you can invoke these functions even on non-String objects. Doing so will imply automatic conversion to a string value prior to changing the case of each character in the resulting string value. For example, you can apply toLowerCase directly on a date like this:

var lower = String.prototype.toLowerCase.apply(new Date());

and which is effectively equivalent to:

var lower = new Date().toString().toLowerCase();

The second form is generally preferred for its simplicity and readability. On earlier versions of IE, the first had the benefit that it could work with a null value. The result of applying toLowerCase or toLocaleLowerCase on null would yield null (and not an error condition).

Yes, any string in JavaScript has a toLowerCase() method that will return a new string that is the old string in all lower case. The old string will remain unchanged.

So, you can do something like:

"Foo".toLowerCase();
document.getElementById('myField').value.toLowerCase();

Simply use JS toLowerCase()
let v = "Your Name" let u = v.toLowerCase(); or
let u = "Your Name".toLowerCase();

const str = 'Your Name';

// convert string to lowercase
const lowerStr = str.toLowerCase();

// print the new string
console.log(lowerStr);

You can use the in built .toLowerCase() method on JavaScript strings. Example:

var x = "Hello";
x.toLowerCase();

In case you want to build it yourself:

function toLowerCase(string) {

    let lowerCaseString = "";

    for (let i = 0; i < string.length; i++) {
        // Find ASCII charcode
        let charcode = string.charCodeAt(i);

        // If uppercase
        if (charcode > 64 && charcode < 97) {
            // Convert to lowercase
            charcode = charcode + 32
        }

        // Back to char
        let lowercase = String.fromCharCode(charcode);

        // Append
        lowerCaseString = lowerCaseString.concat(lowercase);
    }

    return lowerCaseString
}

Try this short way:

var lower = (str+"").toLowerCase();
Related