Strings · Строки
Strings are text
- A string is text inside quotes:
"Ada"or'Ada'. - Join strings with
+— this is called concatenation.
Строки — это текст
- Строка — это текст в кавычках:
"Ada"или'Ada'. - Объединяйте строки с помощью
+— этот процесс называется конкатенацией.
let first = "Ada";
console.log("Hi, " + first + "!"); // → Hi, Ada!
Mind the spaces
+joins text exactly. It never adds a space for you.- Put the space inside the quotes, where you want it to appear.
Следите за пробелами
+соединяет текст точно. Он никогда не добавляет пробел автоматически.- Поместите пробел внутри кавычек там, где он должен появиться.
let pet = "Rex";
console.log("Good dog," + pet + "!"); // → Good dog,Rex! (no space)
console.log("Good dog, " + pet + "!"); // → Good dog, Rex!
Length and capitals
.lengthcounts the characters..toUpperCase()and.toLowerCase()return a copy in CAPITALS or small letters.
Длина и регистр
.lengthподсчитывает количество символов..toUpperCase()и.toLowerCase()возвращают копию текста в ЗАГЛАВНЫХ или строчных буквах.
console.log("hello".length); // → 5
console.log("hello".toUpperCase()); // → HELLO
Index and slice a string · Индексация и срезы строки
Characters are numbered from 0. A slice takes from start up to — but not including — end. · Символы нумеруются начиная с 0. Функция slice берет символы от индекса start до (не включая) индекса end.
Reach inside a string
- Each character has a position, counting from 0:
text[0]is the first one. .slice(start, end)takes the part fromstartup to — but not including —end.
Обращение к символам строки
- У каждого символа есть позиция, нумерация начинается с 0:
text[0]— первый символ. .slice(start, end)извлекает часть строки отstartдо — но не включая —end.
let word = "JAVASCRIPT";
console.log(word[0]); // → J
console.log(word.slice(0, 4)); // → JAVA
Watch out
- Positions start at
0, so the 4th character isword[3]. - String methods return a new string — the original never changes.
Будьте осторожны
- Нумерация позиций начинается с
0, поэтому 4-й символ имеет индексword[3]. - Методы строк возвращают новую строку — исходная строка никогда не изменяется.
Common mistakes
- Index from
0;s.lengthis a property (no()). - Strings cannot be changed in place.
Распространенные ошибки
- Индексация начинается с
0;s.length— это свойство (без()). - Строки нельзя изменить на месте (in-place).
Now you try
- Build and inspect strings.
- Press Check answer to test it.
Теперь попробуйте сами
- Создавайте и просматривайте строки.
- Нажмите Проверить ответ, чтобы протестировать её.
let name = "Sam". Use + to log Hello, then the name then !, so it reads Hello, Sam!. · let name = "Sam". Используйте + для вывода Hello, , затем имени, а затем !, чтобы итоговая строка читалась как Hello, Sam!.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Log how many characters are in the string computer using .length (it is 8). · Выведите количество символов в строке computer с помощью .length (результат равен 8).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Log the string cat in CAPITALS using .toUpperCase() (it is CAT). · Выведите строку cat заглавными буквами с использованием .toUpperCase() (результат равен CAT).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
let word = "code". Log just its first letter using word[0] (it is c). · let word = "code". Выведите только первую букву с помощью word[0] (результат равен c).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.