Javascript метод tolocaleuppercase()

Опис

Всі малі літери перетворюються на великі відповідно до правил певної мови (місцевості), а все решта лишається без змін. Позаяк клас належить до незмінних типів даних, виклик створює новий рядок, лишаючи оригінал без змін. 

Зазвичай метод вертає той самий результат, що й . Втім для деяких мов, як-от турецька, правила перетворення регістра дещо відрізняються від того, що передбачено у Unicode, тож результат буде іншим.

Також зауважте, що перетворення не обов’язково є перетворенням символів 1:1, оскільки деякі символи можуть перетворитись на два (або навіть більше) символів при переведенні у верхній регістр. Таким чином, довжина отриманого рядка може відрізнятись від довжини вхідного рядка. Це також означає, що перетворення не є стабільним, а отже, наприклад, наступне може повернути :

JavaScript toLowerCase

The toLowerCase() method converts all of a string’s characters to lowercase. There are no parameters, and this method does just what you would think.

The toLowerCase() method converts all string characters with decimal Unicode value between 65 («A») and 90 («Z») to their lowercase equivalent (by adding 32 to their decimal Unicode value, from «a» at 97, to «z» at 122). If you have ever worked with the ANSII character set then this should be familiar.

The toLocaleLowerCase() method returns the calling string value converted to lower case, according to any locale-specific case mappings. For the most part you should get the same value as toLowerCase.

The difference is some languages, like Turkish, do not follow the Unicode character codes exactly.

By default the method uses the host system’s default language. You can also pass a specific language to the string to get the local variation:

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Introduction to JavaScript toLowercase()

Javascript provides us with many properties and methods for string object manipulation. We can use them to get the resultant value according to our necessities and requirements. One of the methods available for string manipulation in javascript is toLowerCase() method which converts the string object using which it is called to its equivalent value but in lower case of alphabets.

For example,

Web development, programming languages, Software testing & others

When I declare a variable named sample and initialize it with the value “Hello Students” and then call toLowerCase() method using sample object then it returns me a string object with value “hello students” that is all alphabets in it will be in lower case. Here are the code and output for the same.

Code:

Output:

After clicking the button “Try It”, it will display the string in lower case as the output.

Variants of toLowerCase() method in JavaScript

Below we have to explain variants of JavaScript toLowercase() methods:

  • public String toLowerCase(): This method works the same as the toLocaleLowerCase() method. It considers the default locale as English.
  • Public String toLocaleLowerCase(): The locale is based on the language settings of the browser and may vary sometimes like Turkey, Greek, etc. This method results in the same result in lower cases and varies for some of the characters for different locales like I without the dot in the Turkish language. It considers the default locale as the computer’s current locale.

Example to Implement JavaScript toLowercase()

Below are the explanations for the program to implement:

toLocaleLowerCase()

Code:

Output:

As the default language of my current browser is English the output of toLowerCaseLocale() was similar to toLowerCase(). It would have been different if the browser’s current locale would be different like Turkey, Greek or else.

Popular Course in this category

JavaScript Training Program (39 Courses, 23 Projects)39 Online Courses | 23 Hands-on Projects | 225+ Hours | Verifiable Certificate of Completion | Lifetime Access 4.5 (4,284 ratings)

Course Price View Course

Related Courses
Angular JS Training Program (9 Courses, 7 Projects)Vue JS Training (1 Courses, 3 Project)

Internal Details of toLowerCase() Method Work

  • Internally, the string is converted to character array and then each character is compared and converted to the required
  • Finally, after the final array is formed containing all the desired characters in lower case, it is converted to a string and new string is
  • Hence, it is necessary to remember that the original string object supplied to this method is not changed or modified instead a new string object is created and returned.

Code:

Explanation to the above code: The above java code represents how internally javascript code must be working. MIN_HIGH_SURROGATE. In the UTF-16 encoding, the minimum value of a Unicode high-surrogate code unit constant is ‘\uD800’. MAX_HIGH_SURROGATE. In the UTF-16 encoding, the maximum value of a Unicode high-surrogate code unit constant is ‘\uDBFF’. MIN_SUPPLEMENTARY_CODE_POINT. In the UTF-16 encoding, the minimum value of a Unicode supplementary code point, constant is U+10000.

Conclusion

We can conclude that for both the methods toLowerCase() and toUpperCase() and their variants for locale the internal working is very similar. In both the methods the symbols and numbers are retained only the characters are converted to lower case or upper case. We should keep in mind that both the methods do not modify the characters of original strings. Instead, both of them create a new String object which contains the same value with the characters in their desired format. Both these methods work well and are introduced in ECMAScript 1 javascript version.

Recommended Articles

This is a guide to JavaScript toLowercase(). Here we discuss an introduction, variant methods, and example and internal detail of JavaScript toLowercase() with appropriate example. You can also go through our other related articles to learn more –

  1. Arithmetic in JavaScript
  2. JavaScript Arrow Function
  3. Bitwise Operators in JavaScript
  4. Square Root in JavaScript

JavaScript Training Program (39 Courses, 23 Projects)

39 Online Courses

23 Hands-on Projects

225+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

The typeof Operator

The typeof operator returns the type of a variable, object, function or
expression:

Example

typeof «John»                
// Returns string
typeof 3.14                  
// Returns number
typeof
NaN                   
// Returns number
typeof false                 
// Returns boolean
typeof            // Returns object
typeof {name:’John’, age:34} 
// Returns objecttypeof new Date()            
// Returns objecttypeof function () {}         // Returns function
typeof myCar                 
// Returns undefined (if myCar is not declared)
typeof null                  
// Returns object

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined

You cannot use typeof to define if a JavaScript object is an
array (or a date).

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5, the table below explains the arithmetic operators:

Operator Description Example Result in y Result in x Try it
+ Addition x = y + 2 y = 5 x = 7 Try it »
Subtraction x = y — 2 y = 5 x = 3 Try it »
* Multiplication x = y * 2 y = 5 x = 10 Try it »
Division x = y / 2 y = 5 x = 2.5 Try it »
% Modulus (division remainder) x = y % 2 y = 5 x = 1 Try it »
++ Increment x = ++y y = 6 x = 6 Try it »
x = y++ y = 6 x = 5 Try it »
Decrement x = —y y = 4 x = 4 Try it »
x = y— y = 4 x = 5 Try it »

For a tutorial about arithmetic operators, read our
JavaScript Arithmetic Tutorial.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Методи екземплярів

Вертає символ (рівно одну кодову одиницю UTF-16), розташований за вказаним індексом .
Вертає число, яке є значенням кодової одиниці UTF-16, розташованої за вказаним індексом .
Вертає невід’ємне ціле число, яке є значенням коду символу UTF-16, що починається на вказаній позиції .
Об’єднує текст двох (або більше) рядків та повертає новий рядок.
Визначає, чи містить рядок, що викликав метод, рядок .
Визначає, чи завершується рядок символами рядка .
Вертає індекс всередині об’єкта , що викликав метод, першого знайденого значення , або , якщо воно не знайдене.
Вертає індекс всередині об’єкта , що викликав метод, останнього знайденого значення , або , якщо значення не знайдене.
Вертає число, що вказує, чи розташований рядок  перед, після, чи однаково, відносно наданого рядка у відсованій послідовності.
Використовується, щоб зіставити регулярний вираз  з рядком.
Вертає ітератор усіх збігів з регулярним виразом.
Вертає рядкове значення, на якому викликано метод, у формі нормалізації Юнікоду.
Доповнює поточний рядок наданим рядком з кінця та повертає новий рядок, що має довжину .
Доповнює поточний рядок наданим рядком з початку та повертає новий рядок, що має довжину .
Повертає рядок, що складається з елементів об’єкта, повторених  разів.
Використовується, щоб замінити заміною . може бути рядком або регулярним виразом, а  може бути рядком чи функцією.
Використовується, щоб замінити усі збіги з шаблоном заміною .  може бути рядком або регулярним виразом, а  може бути рядком або функцією.
Шукає збіг між регулярним виразом  та рядком, що викликав метод.
Вирізає частину рядка та повертає новий рядок.
Вертає масив рядків, заповнених розділенням початкового рядка підрядком .
Визначає, чи починається рядок з символів рядка .
Повертає вказану кільксть символів на початку рядка з вказаної позиції.
Повертає рядок, що містить символи рядка від вказаного індекса, або між вказаними індексами.

Символи рядка переводяться до нижнього регістра відповідно до поточних регіональних налаштувань.

Для більшості мов результат буде такий самий, як у .

Символи рядка переводяться до верхнього регістра відповідно до поточних регіональних налаштувань.

Для більшості мов результат буде такий самий, як у .

Повертає значення рядка, переведене до нижнього регістра.
Повертає рядкове представлення вказаного об’єкта. Заміщує метод .
Повертає значення рядка, переведене до верхнього регістра.
Прибирає пробіли з початку та кінця рядка. Частина стандарту ECMAScript 5.
Видаляє пробіли з початку рядка.
Видаляє пробіли з кінця рядка.
Повертає просту величину вказаного об’єкта. Заміщує метод .
Повертає новий об’єкт , який перебирає коди символів рядка, повертаючи кожний код символа рядкового значення.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

6.2 Метод String.format() и класс StringFormatter

И еще один интересный метод класса String — .

Допустим, у вас есть различные переменные с данными. Как вывести их на экран одной строкой? Например, у нас есть данные (левая колонка) и желаемый вывод (правая колонка):

Код Вывод на экран

Скорее всего, ваш код будет выглядеть примерно так:

Код программы

Такой код не слишком читабельный. Более того, если бы имена переменных были длиннее, код стал бы еще сложнее:

Код программы

Не очень читаемо, не так ли?

Однако в реальных программах такая ситуация встречается часто, поэтому я хочу рассказать о способе, как проще и короче записать этот код.

У класса String есть статический метод : он позволяет задать шаблон объединения строки с данными. Общий вид этой команды такой:

Пример:

Код Результат

В метод первым параметром передают строку-шаблон, которая содержит весь нужный текст, а в местах, где нужно вставлять данные, написаны специальные символы типа , и т.п.

Вот эти и метод и заменяют на параметры, которые идут следом за строкой-шаблоном. Если нужно подставить строку, мы пишем , если число — . Пример:

Код Результат
будет равна «a=1, b=4, c=3»

Вот краткий список параметров, которые можно использовать внутри шаблона:

Символ Обозначение
%s
%d целое число: , , ,
%f вещественное число: ,
%b
%c
%t
%% Символ

Эти параметры указывают на тип данных, но есть еще параметры, которые указывают на порядок данных. Чтобы взять параметр по его номеру (нумерация начинается с единицы), нужно записать «%1$d» вместо «%d». Пример:

Код Результат
будет равна «a=13, b=12, c=11»

возьмет 3-й параметр-переменную, возьмет второй параметр. возьмет самый первый параметр-переменную. Параметры шаблона , обращаются к переменным-параметрам независимо от параметров шаблона типа или

JavaScript toUpperCase

JavaScript’s toUpperCase() method converts all of a string’s characters to uppercase. There are no parameters, and this method also does just what you would think. This is an all caps converting method.

The toUpperCase() method does the opposite of the toLowerCase method. It converts all string characters with decimal Unicode value between 97 («a») and 122 («z») to their uppercase equivalent (by substracting 32 from their decimal Unicode value, from «A» at 65, to «Z» at 90).

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings, just like it’s lower case counterpart.

The toLowerCase and toUpperCase methods can serve as your base to perform more specific case manipulations.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector