此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Strings are text
- A string is text inside quotes:
"Ada"or'Ada'. - Join strings with
+— this is called concatenation.
English
let first = "Ada";
console.log("Hi, " + first + "!"); // → Hi, Ada!
English
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.
English
let pet = "Rex";
console.log("Good dog," + pet + "!"); // → Good dog,Rex! (no space)
console.log("Good dog, " + pet + "!"); // → Good dog, Rex!
English
Length and capitals
.lengthcounts the characters..toUpperCase()and.toLowerCase()return a copy in CAPITALS or small letters.
English
console.log("hello".length); // → 5
console.log("hello".toUpperCase()); // → HELLO
探索
索引和切片一个字符串
Characters are numbered from 0. A slice takes from start up to — but not including — end.
English
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.
![HELLO with indexes 0 to 4; word.length is 5, word[0] is "H", word.slice(1, 4) is "ELL"](/static/code/javascript/string-index.png)
English
let word = "JAVASCRIPT";
console.log(word[0]); // → J
console.log(word.slice(0, 4)); // → JAVA
English
Watch out
- Positions start at
0, so the 4th character isword[3]. - String methods return a new string — the original never changes.
English
Common mistakes
- Index from
0;s.lengthis a property (no()). - Strings cannot be changed in place.
English
Now you try
- Build and inspect strings.
- Press Check answer to test it.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
let name = "Sam". Use + to log Hello, then the name then !, so it reads Hello, Sam!.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Log how many characters are in the string computer using .length (it is 8).
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Log the string cat in CAPITALS using .toUpperCase() (it is CAT).
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
let word = "code". Log just its 第一个 letter using word[0] (it is c).
点击“运行”查看此处输出。