To lower case in javascript

String.prototype.toLocaleLowerCase()

The toLocaleLowerCase() method returns the calling string value converted to lower case, according to any locale-specific case mappings.

Try it

Syntax

toLocaleLowerCase() toLocaleLowerCase(locales) 

Parameters

A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

Unlike other methods that use the locales argument, toLocaleLowerCase() does not allow locale matching. Therefore, after checking the validity of the locales argument, toLocaleLowerCase() always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.

Return value

A new string representing the calling string converted to lower case, according to any locale-specific case mappings.

Description

The toLocaleLowerCase() method returns the value of the string converted to lower case according to any locale-specific case mappings. toLocaleLowerCase() does not affect the value of the string itself. In most cases, this will produce the same result as toLowerCase() , but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.

Читайте также:  Kotlin transform map to map

Examples

Using toLocaleLowerCase()

"ALPHABET".toLocaleLowerCase(); // 'alphabet' "\u0130".toLocaleLowerCase("tr") === "i"; // true "\u0130".toLocaleLowerCase("en-US") === "i"; // false const locales = ["tr", "TR", "tr-TR", "tr-u-co-search", "tr-x-turkish"]; "\u0130".toLocaleLowerCase(locales) === "i"; // true 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 1, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript String toLowerCase()

The toLowerCase() method converts a string to lowercase letters.

The toLowerCase() method does not change the original string.

See Also:

Syntax

Parameters

Return Value

Browser Support

toLowerCase() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

JavaScript toLowerCase() – How to Convert a String to Lowercase and Uppercase in JS

Dionysia Lemonaki

Dionysia Lemonaki

JavaScript toLowerCase() – How to Convert a String to Lowercase and Uppercase in JS

This article explains how to convert a string to lowercase and uppercase characters.

We’ll also go over how to make only the first letter in a word uppercase and how to make the first letter of every word in a sentence uppercase.

How to use the toLowerCase() method in JavaScript

The toLowerCase method converts a string to lowercase letters.

The general syntax for the method looks like this:

The toLowerCase() method doesn’t take in any parameters.

Strings in JavaScript are immutable. The toLowerCase() method converts the string specified into a new one that consists of only lowercase letters and returns that value.

It means that the old, original string is not changed or affected in any way.

let myGreeting = 'Hey there!'; console.log(myGreeting.toLowerCase()); //output //hey there! 

The string myGreeting consists of only one capital letter that gets converted to lowercase.

Any letters that are already lowercase are not affected by the toLowerCase() method, only uppercase ones. These letters preserve their original form.

The string in the example below consists of all capital letters. They are all then converted to lowercase when the toLowerCase() method is applied.

const anotherGreeting = 'GOOD MORNING!!'; console.log(anotherGreeting.toLowerCase()); //output //good morning!! 

How to use the toUpperCase() method in JavaScript

The toUpperCase() method is similar to the toLowerCase() method but it instead converts the string value to uppercase.

The general syntax for calling the method looks like this:

It doesn’t take in any parameters.

As strings in JavaScript are immutable, the toLowerCase() method does not change the value of the string specified.

It instead returns a new value. The string specified is converted to a new one whose contents consist of only all uppercase letters. This means that there will now be two strings: the original and the newly converted capitalized one.

console.log('I am shouting!'.toUpperCase()); //output //I AM SHOUTING! 

Any capital letters already in the string will not be affected and will remain unchanged when the toLowerCase() method gets called.

How to capitalize only the first letter in a string in JavaScript

What if you want to make only the first letter of a string a capital?

Below is a simple example that shows you one way to do just that.

Say there is a variable called myGreeting with the string value of hello , in all lowercase letters.

You first locate and extract the first letter of that string by using its index. Then you call the toUpperCase() method on that specific letter.

As a reminder, indexing in JavaScript (and most programming languages) starts at 0 , so the first letter has an index of 0 .

Save this operation in a new variable called capFirstLetter .

let capFirstLetter = myGreeting[0].toUpperCase(); console.log(capFirstLetter); // returns the letter 'H' in this case 

Next, you want to isolate and cut off that first character and keep the remainder of the string.

One way to do this is by using the slice() method. This creates a new string starting from the index specified until the end of the word.

You want to start from the second letter until the end of the value.

In this case, the argument you should pass to slice() is an index of 1 since that is the index of the second letter.

This way, the first character is excluded altogether. A new string is returned without it but containing the rest of the characters – minus that first letter.

Then save that operation to a new variable.

let restOfGreeting = myGreeting.slice(1); console.log(restOfGreeting); //returns the string 'ello' 

By combining the two new variables with concatenation, you get a new string with only the first letter capitalized.

let newGreeting = capFirstLetter + restOfGreeting; console.log(newGreeting); //Hello 

Another way is to combine the steps from above and isolate them in a function.

The function gets created just once. The function then returns a new string with the first letter capitalized.

The amount of code you need to write is substantially less while also being able to pass in any string as an argument without writing repetitive code.

function capFirst(str) < return str[0].toUpperCase() + str.slice(1); >console.log(capFirst('hello')); //output //Hello 

How to capitalize the first letter of every word in JavaScript

But how do you make the first letter of every word in a sentence uppercase?

The method shown in the section above won’t work as it doesn’t deal with multiple words, just a single word in a sentence.

Say you have a sentence like the one below. You want to capitalize every first word in the sentence.

let learnCoding = 'learn to code for free with freeCodeCamp'; 

The first step is to split the sentence into individual words and work with each one separately.

For that, you use the split() method and pass a space as an argument. It means that with every space in the sentence provided, an item gets passed into a new array.

It splits the sentence based on blank spaces.

Create a new variable and store the new array.

let splitLearnCoding = learnCoding.split(" "); console.log(splitLearnCoding); //['learn', 'to', 'code', 'for', 'free', 'with', 'freeCodeCamp'] 

Now from that sentence, there is a new array of words that allows you to manipulate each word on its own, separately.

Since there is now a new array, you can use the map() method to iterate over each individual item inside it.

In the map() method, you use the same procedure shown in the section above to take each word individually, capitalize the first letter, and return the rest of the word.

let capSplitLearnCoding = splitLearnCoding.map(word => < return word[0].toUpperCase() + word.slice(1); >) console.log(capSplitLearnCoding); //['Learn', 'To', 'Code', 'For', 'Free', 'With', 'FreeCodeCamp'] 

The first letter of every word is now capitalized.

All that is left now is to combine the words in the array together in a single sentence again.

For that you use the join() method and pass a space as the argument.

let learnCodingNew = capSplitLearnCoding.join(" "); console.log(learnCodingNew); //Learn To Code For Free With FreeCodeCamp 

As shown in the section above, you can also create a function that combines all theses steps. You will then be able to pass as an argument any string and each first word in it will be uppercase.

function capFirstLetterInSentence(sentence) < let words = sentence.split(" ").map(word =>< return word[0].toUpperCase() + word.slice(1); >) return words.join(" "); > console.log(capFirstLetterInSentence("i am learning how to code")); //I Am Learning How To Code 

Conclusion

And there you have it! This is how you use the toLowerCase() and toUpperCase() methods in JavaScript.

You learned how to capitalize the first letter of a word and capitalize the first letter of each word in a sentence.

If you want to learn JavaScript and gain a better understanding of the language, freeCodeCamp has a free JavaScript Certification.

You’ll start from the basics as an absolute beginner to the language and then advance to more complex subjects such as Object Oriented Programming, Functional Programming, Data Structures, Algorithms, and helpful Debugging techniques.

In the end, you’ll build five projects to put your skills to practice.

Thanks for reading, and happy learning!

Источник

toLowerCase

А слабо дать описание. Например нужен для этого, используется там-то.

Метод toLowerCase()
Преобразует все буквы в строке к нижнему регистру.
Метод toLowerCase не применяется к знакам, отличным от букв.
В следующем примере демонстрируется действие метода toLowerCase.

var text = «This is a STRING.»;
var str = text. toLowerCase();
document.write(str);

toLowerCase не работает в ие. Есть ли альтернатива?

Проверил toLowerCase(), toUpperCase() в IE7. Всё работает.

Но, если очень нужно, то можно создать такую функцию MyToLowerCase() (аналогично и MyToUpperCase()):

function MyToLowerCase(s) var t=»;
for(var i=0;i

Проверил toLowerCase(), toUpperCase() в IE7. Всё работает.

Но, если очень нужно, то можно создать такую функцию MyToLowerCase() (аналогично и MyToUpperCase()):

function MyToLowerCase(s) < var t=''; for(var i=0;i> return t; >

Можно переписать этот код изящнее:

function toLow(s) < var charMap = < 'А': 'a', 'Б': 'б', 'В': 'в', 'Г': 'г', 'Я': 'Я' >; var modSt = ''; for(var i = 0;i < s.length; i++) < var str = s.charAt(i); if (charMap[str]) < modSt += charMap[str]; >else < modSt += str; >> return modSt; >

возвращает модифицированную строку и/или модифицирует существующую?

javascript не может изменять строки он всегда создает новый экземпляр строки

Метод toLowerCase()
Преобразует все буквы в строке к нижнему регистру.
Метод toLowerCase не применяется к знакам, отличным от букв.
В следующем примере демонстрируется действие метода toLowerCase.

var text = «This is a STRING.»;
var str = text. toLowerCase();
document.write(str);

Товарищи, доброго времени суток!
Помогите, пожалуйста! Нужен скрипт для mongodb, который:
1. преобразует значение поля А в нижний регистр;
2. выполнит апдейт поля А, записав туда новое значение (в нижнем регистре).
плиз плиз плиз.

Источник

Оцените статью