Strings · 字符串
Strings are text
- A string is text inside quotes:
"Ada"or'Ada'. - Join strings with
+— this is called concatenation.
字符串就是文本
- 字符串(string)是引号里的文本:
"Ada"或'Ada'。 - 用
+把字符串连起来 —— 这叫做拼接(concatenation)。
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 开始编号。切片取从 start 到 end(不包含 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(但不包含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是属性(不带())。 - 字符串不能原地修改。
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). · 用 .length 打印字符串 computer 有多少个字符(是 8)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Log the string cat in CAPITALS using .toUpperCase() (it is CAT). · 用 .toUpperCase() 把字符串 cat 转成大写后打印(是 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. · 点击“运行”查看此处输出。