1411

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

Example: "Your Name" to "your name"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Derek
  • 16,181
  • 3
  • 27
  • 36
  • does a question like this *really* deserve to earn the OP 14,000 rep? That's around 130 rep per character typed (yet with no apparent attempt to solve on his own... or to Google the solution) and continues to earn the OP a title of **"Top 2% on the site"** ... even though he hasn't even logged in, for over 5 years! – ashleedawg Dec 16 '22 at 01:06

16 Answers16

1820
var lowerCaseName = "Your Name".toLowerCase();
John Topley
  • 113,588
  • 46
  • 195
  • 237
  • 33
    Consider this also, "toLowerCase does not affect the value of the string str itself". This is base on a documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase – Cary Bondoc Jun 27 '14 at 00:52
  • 1
    what is time and space complexity of `toLowerCase()` function? – Rami Chasygov Apr 04 '18 at 17:41
  • 11
    @RamzanChasygov It is both O(n) and faster than reimplementing it in JavaScript, unless you have a JavaScript engine programmed by very intelligent idiots. – wizzwizz4 Apr 09 '18 at 12:13
  • 6
    A safer way to invoke `toLowerCase()` on variables would be `(varName || '').toLowerCase()`; – Dinesh Pandiyan Dec 22 '18 at 02:31
434

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).

Atif Aziz
  • 36,108
  • 16
  • 64
  • 74
  • The part about `String.prototype.toLowerCase.apply(null)` returning `null` doesn't appear to be correct. It throws a `TypeError` exception when I try it. – JohnnyHK Jul 20 '13 at 15:52
  • 2
    @JohnnyHK You're right. That bit used to hold true on earlier versions of IE where it was tested at the time the answer was originally posted. I've updated the answer to reflect your feedback. Thanks. – Atif Aziz Dec 18 '13 at 12:28
31

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

So, you can do something like:

"Foo".toLowerCase();
document.getElementById('myField').value.toLowerCase();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pkaeding
  • 36,513
  • 30
  • 103
  • 141
21

toLocaleUpperCase() or lower case functions don't behave like they should do. For example, on my system, with Safari 4, Chrome 4 Beta, and Firefox 3.5.x, it converts strings with Turkish characters incorrectly. The browsers respond to navigator.language as "en-US", "tr", "en-US" respectively.

But there isn't any way to get user's Accept-Lang setting in the browser as far as I could find.

Only Chrome gives me trouble although I have configured every browser as tr-TR locale preferred. I think these settings only affect the HTTP header, but we can't access to these settings via JavaScript.

In the Mozilla documentation it says "The characters within a string are converted to ... while respecting the current locale. For most languages, this will return the same as ...". I think it's valid for Turkish, and it doesn't differ if it's configured as en or tr.

In Turkish it should convert "DİNÇ" to "dinç" and "DINÇ" to "dınç" or vice-versa.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sanilunlu
  • 725
  • 1
  • 6
  • 8
  • 1
    `Accept-Language` and `navigator.language` are two completely separate settings. `Accept-Language` reflects the user's chosen preferences for what languages they want to receive in web pages (and this setting is unfortuately inaccessible to JS). `navigator.language` merely reflects which localisation of the web browser was installed, and should generally not be used for anything. Both of these values are unrelated to the system locale, which is the bit that decides what `toLocaleLowerCase()` will do; that's an OS-level setting out of scope of the browser's prefs. – bobince Sep 29 '10 at 22:15
  • I thought Accept-Language and navigator.language should be somehow related. You can configure the default language in order via browsers' settings screens, but so you can't configure what navigator.language should respond. I think there should be another form of the function toLowerCase() which gets a locale parameter. – sanilunlu Mar 21 '11 at 13:33
  • Yeah, there should really. Unfortunately locale-related features in JavaScript are weak, poorly-specified and generally unreliable. – bobince Mar 21 '11 at 19:40
17

Just an example for toLowerCase(), toUpperCase() and a prototype for the not yet available toTitleCase() or toProperCase():

String.prototype.toTitleCase = function() {
  return this.split(' ').map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ');
}

String.prototype.toPropperCase = function() {
  return this.toTitleCase();
}

var OriginalCase = 'Your Name';
var lowercase = OriginalCase.toLowerCase();
var upperCase = lowercase.toUpperCase();
var titleCase = upperCase.toTitleCase();

console.log('Original: ' + OriginalCase);
console.log('toLowerCase(): ' + lowercase);
console.log('toUpperCase(): ' + upperCase);
console.log('toTitleCase(): ' + titleCase);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ewwink
  • 18,382
  • 2
  • 44
  • 54
  • 3
    -1 this code is very prone to errors with everything non-ASCII. For example, with the German input "die straße", you will get "Die Strasse" as the title case. Correct would be "Die Straße". Apart from that, prototype pollution is nowadays frowned upon. – ComFreek Apr 18 '20 at 13:40
  • @ComFreek It could've been faulty back then, but as for now, it works fairly well with `node V17` and `chrome V104` – polendina Aug 18 '22 at 17:05
13

I paid attention that lots of people are looking for strtolower() in JavaScript. They are expecting the same function name as in other languages, and that's why this post is here.

I would recommend using a native JavaScript function:

"SomE StriNg".toLowerCase()

Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into JavaScript)

function strToLower (str) {
    return String(str).toLowerCase();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dan
  • 55,715
  • 40
  • 116
  • 154
9

Methods or functions: toLowerCase() and toUpperCase()

Description: These methods are used to cover a string or alphabet from lowercase to uppercase or vice versa. E.g., "and" to "AND".

Converting to uppercase:

Example code:

<script language=javascript>
    var ss = " testing case conversion method ";
    var result = ss.toUpperCase();
    document.write(result);
</script>

Result: TESTING CASE CONVERSION METHOD

Converting to lowercase:

Example Code:

<script language=javascript>
    var ss = " TESTING LOWERCASE CONVERT FUNCTION ";
    var result = ss.toLowerCase();
    document.write(result);
</script>

Result: testing lowercase convert function

Explanation: In the above examples,

  • toUpperCase() method converts any string to "UPPER" case letters.

  • toLowerCase() method converts any string to "lower" case letters.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JackSparrow
  • 948
  • 1
  • 11
  • 9
8

Note that the function will only work on string objects.

For instance, I was consuming a plugin, and was confused why I was getting a "extension.tolowercase is not a function" JavaScript error.

 onChange: function(file, extension)
    {
      alert("extension.toLowerCase()=>" + extension.toLowerCase() + "<=");

Which produced the error "extension.toLowerCase is not a function". So I tried this piece of code, which revealed the problem!

alert("(typeof extension)=>" + (typeof extension) + "<=");;

The output was "(typeof extension)=>object<=" - so aha, I was not getting a string var for my input. The fix is straightforward though - just force the darn thing into a String!:

var extension = String(extension);

After the cast, the extension.toLowerCase() function worked fine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Gorbas
  • 1,694
  • 20
  • 16
4

Option 1: Using toLowerCase()

var x = 'ABC';
x = x.toLowerCase();

Option 2: Using your own function

function convertToLowerCase(str) {
  var result = '';

  for (var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code > 64 && code < 91) {
      result += String.fromCharCode(code + 32);
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

Call it as:

x = convertToLowerCase(x);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siddhartha
  • 1,473
  • 14
  • 10
  • 1
    The first option has already been mentioned in other answers, the second option fails badly for everything non-ASCII. – ComFreek Apr 18 '20 at 13:41
3

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

Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
0
const str = 'Your Name';

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

// print the new string
console.log(lowerStr);
Force Bolt
  • 1,117
  • 9
  • 9
0

Simply you can use built-in methods of javascript like toLowerCase()

let str=Hello World;
let lowercasestr=str.toLowerCase()
console.log("lowercasestr")
moaz ahmad
  • 174
  • 5
-2

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

var x = "Hello";
x.toLowerCase();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Praveen
  • 100
  • 8
-2

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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Javier Giovannini
  • 2,302
  • 1
  • 19
  • 21
-3

Try this short way:

var lower = (str+"").toLowerCase();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdurahman Popal
  • 2,859
  • 24
  • 18
  • Please explain your answer. For instance, why is `+ ""` necessary? How is it different from previous answers? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/55868778/edit), not here in comments (*********** ***without*** *********** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Dec 08 '22 at 22:08
-4

Try

<input type="text" style="text-transform: uppercase">  <!-- uppercase -->
<input type="text" style="text-transform: lowercase">  <!-- lowercase -->

Demo - JSFiddle

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Some Java Guy
  • 4,992
  • 19
  • 71
  • 108