javascript 字符串(string) 对象
string 对象用于处理已有的字符块。
javascript 字符串
一个字符串用于存储一系列字符就像 "john doe".
一个字符串可以使用单引号或双引号:
实例
var
carname="volvo xc60";
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="he is called 'johnny'";
var answer='he is called "johnny"';
或者你可以在字符串中使用转义字符()使用引号:
实例
var answer='it's alright';
var answer="he is called "johnny"";
var answer="he is called "johnny"";
字符串(string)
字符串(string)使用长度属性length来计算字符串的长度:
实例
var txt="hello world!";
document.write(txt.length);
var txt="abcdefghijklmnopqrstuvwxyz";
document.write(txt.length);
document.write(txt.length);
var txt="abcdefghijklmnopqrstuvwxyz";
document.write(txt.length);
在字符串中查找字符串
字符串使用 indexof() 来定位字符串中某一个指定的字符首次出现的位置:
实例
var str="hello world, welcome to the universe.";
var n=str.indexof("welcome");
var n=str.indexof("welcome");
如果没找到对应的字符函数返回-1
lastindexof() 方法在字符串末尾开始查找字符串出现的位置。
内容匹配
match()函数用来查找字符串中特定的字符,并且如果找到的话,则返回这个字符。
实例
var str="hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("world") + "<br>");
document.write(str.match("world!"));
document.write(str.match("world") + "<br>");
document.write(str.match("world") + "<br>");
document.write(str.match("world!"));
替换内容
replace() 方法在字符串中用某些字符替换另一些字符。
实例
str="please visit microsoft!"
var n=str.replace("microsoft","runoob");
var n=str.replace("microsoft","runoob");
字符串大小写转换
字符串大小写转换使用函数 touppercase() / tolowercase():
实例
var txt="hello world!"; //
string
var txt1=txt.touppercase(); // txt1 文本会转换为大写
var txt2=txt.tolowercase(); // txt2 文本会转换为小写
var txt1=txt.touppercase(); // txt1 文本会转换为大写
var txt2=txt.tolowercase(); // txt2 文本会转换为小写
字符串转为数组
字符串使用split()函数转为数组:
实例
txt="a,b,c,d,e" // string
txt.split(","); // 使用逗号分隔
txt.split(" "); // 使用空格分隔
txt.split("|"); // 使用竖线分隔
txt.split(","); // 使用逗号分隔
txt.split(" "); // 使用空格分隔
txt.split("|"); // 使用竖线分隔
特殊字符
javascript 中可以使用反斜线()插入特殊符号,如:撇号,引号等其他特殊符号。
查看如下 javascript 代码:
var txt="we are the so-called "vikings" from the north.";
document.write(txt);
document.write(txt);
在javascript中,字符串的开始和停止使用单引号或双引号。这意味着,上面的字符串将被切成: we are the so-called
解决以上的问题可以使用反斜线来转义引号:
var txt="we are the so-called "vikings" from the north.";
document.write(txt);
document.write(txt);
javascript将输出正确的文本字符串:we are the so-called "vikings" from the north.
下表列出其他特殊字符,可以使用反斜线转义特殊字符:
| 代码 | 输出 |
|---|---|
| ' | 单引号 |
| " | 双引号 |
| 斜杆 | |
| n | 换行 |
| r | 回车 |
| t | tab |
| b | 空格 |
| f | 换页 |
字符串属性和方法
属性:
- length
- prototype
- constructor
方法:
- charat()
- charcodeat()
- concat()
- fromcharcode()
- indexof()
- lastindexof()
- match()
- replace()
- search()
- slice()
- split()
- substr()
- substring()
- tolowercase()
- touppercase()
- valueof()
更多方法与属性介绍可以参考:javascript string 对象
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!