- Object-Oriented JavaScript(Second Edition)
- Stoyan Stefanov Kumar Chetan Sharma
- 466字
- 2021-08-13 16:19:28
Strings
A string is a sequence of characters used to represent text. In JavaScript, any value placed between single or double quotes is considered a string. This means that 1
is a number, but "1"
is a string. When used with strings, typeof
returns the string "string"
:
> var s = "some characters"; > typeof s; "string" > var s = 'some characters and numbers 123 5.87'; > typeof s; "string"
Here's an example of a number used in the string context:
> var s = '1';
> typeof s;
"string"
If you put nothing in quotes, it's still a string (an empty string):
> var s = ""; typeof s;
"string"
As you already know, when you use the plus sign with two numbers, this is the arithmetic addition operation. However, if you use the plus sign with strings, this is a string concatenation operation, and it returns the two strings glued together:
> var s1 = "web"; > var s2 = "site"; > var s = s1 + s2; > s; "website" > typeof s; "string"
The dual purpose of the +
operator is a source of errors. Therefore, if you intend to concatenate strings, it's always best to make sure that all of the operands are strings. The same applies for addition; if you intend to add numbers, make sure the operands are numbers. You'll learn various ways to do so further in the chapter and the book.
String conversions
When you use a number-like string (for example "1"
) as an operand in an arithmetic operation, the string is converted to a number behind the scenes. This works for all arithmetic operations except addition, because of its ambiguity:
> var s = '1'; > s = 3 * s; > typeof s; "number" > s; 3 > var s = '1'; > s++; > typeof s; "number" > s; 2
A lazy way to convert any number-like string to a number is to multiply it by 1 (another way is to use a function called parseInt()
, as you'll see in the next chapter):
> var s = "100"; typeof s; "string" > s = s * 1; 100 > typeof s; "number"
If the conversion fails, you'll get NaN
:
> var movie = '101 dalmatians';
> movie * 1;
NaN
You convert a string to a number by multiplying by 1. The opposite—converting anything to a string—can be done by concatenating it with an empty string:
> var n = 1; > typeof n; "number" > n = "" + n; "1" > typeof n; "string"
Special strings
There are also strings with special meanings, as listed in the following table:

There are also additional characters that are rarely used: \b
(backspace), \v
(vertical tab), and \f
(form feed).
- 圖解Java數(shù)據(jù)結(jié)構(gòu)與算法(微課視頻版)
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- 跟老齊學(xué)Python:輕松入門
- Bulma必知必會(huì)
- 秒懂設(shè)計(jì)模式
- Kotlin Standard Library Cookbook
- Xamarin.Forms Projects
- C++從入門到精通(第5版)
- Python應(yīng)用開發(fā)技術(shù)
- Flink入門與實(shí)戰(zhàn)
- Java面向?qū)ο蟪绦蛟O(shè)計(jì)教程
- JavaScript Mobile Application Development
- C語言程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)
- Mastering Machine Learning with scikit-learn
- Eclipse開發(fā)(學(xué)習(xí)筆記)