
String 对象用于处理已有的字符块。
一个字符串用于存储一系列字符就像 "John Doe".
一个字符串可以使用单引号或双引号:
var carname="Volvo XC60";
var carname='Volvo XC60';你使用位置(索引)可以访问字符串中任何的字符:
var character=carname[7];字符串的索引从零开始, 所以字符串第一字符为 [0],第二个字符为 [1], 等等。
你可以在字符串中使用引号,如下实例:
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';或者你可以在字符串中使用转义字符(\)使用引号:
var answer='It\'s alright';
var answer="He is called \"Johnny\"";字符串(String)使用长度属性length来计算字符串的长度:
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);Javascript 中可以使用反斜线(\)插入特殊符号,如:撇号,引号等其他特殊符号。
查看如下 JavaScript 代码:
var txt="We are the so-called "Vikings" from the north."; document.write(txt);
在JavaScript中,字符串的开始和停止使用单引号或双引号。这意味着,上面的字符串将被切成: We are the so-called
解决以上的问题可以使用反斜线来转义引号:
var txt="We are the so-called \"Vikings\" from the north."; document.write(txt);
JavaScript将输出正确的文本字符串:We are the so-called "Vikings" from the north.
下表列出其他特殊字符,可以使用反斜线转义特殊字符:
代码 | 输出 |
|---|---|
\' | 单引号 |
\" | 双引号 |
\\ | 斜杆 |
\n | 换行 |
\r | 回车 |
\t | tab |
\b | 空格 |
\f | 换页 |
属性:
方法:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。