一、字符串操作
1.字符串创建
var s1="hello"
var s2=new String("hello")
2.属性
s1.length 获取字符串的长度
3、方法
(1)获取字符
charAt():返回给定位置的字符
charCodeAt():返回字符编码
[](下标) var s1="hello"
01234 ---索引或下标值
(2)操作字符串
+ 进行字符串连接
concat():用于将一个或多个字符串拼接起来,并返回拼接后得到的新字符串。
var s1="hello"
// var s2=s1.concat("world")
var s2=s1.concat("world","student","!")
console.log(s2);
(3)子字符串
从0开始
substr(起始位置,长度):截取从起始位置截取指定的长度的子字符串
如起始位置为负数,则倒数,第二个参数为负数则为空
s1="hello world"
console.log( s1.substr(3));//lo world
console.log(s1.substr(3,6));//lo wor
console.log(s1.substr(0));//hello world
console.log(s1.substr(-3));//rld
console.log(s1.substr(3,-4));//空
console.log(s1.substr(8,3));//rld
从0开始
substring(起始位置,终止位置):起始包含,终止不包含,遇到负数会自动转换为0
起始如大于终止,则自动调换
s1="hello world"
console.log(s1.substring(3));//lo world
console.log(s1.substring(3,7));//lo w
console.log(s1.substring(0));//hello world
console.log(s1.substring(-3));//hello world
console.log(s1.substring(3,-4));//hel 不识别负数
console.log(s1.substring(8,3));//lo wo
slice(起始位置,终止位置) 截取 起始包含,终止不包含
识别负数
s1="hello world"
console.log(s1.slice(3));//lo world
console.log(s1.slice(3,7));//lo w
console.log(s1.slice(0));//hello world
console.log(s1.slice(-3));//rld
console.log(s1.slice(3,-4));//lo w
console.log(s1.slice(8,3));//超过截取位置为空
console.log(s1.slice(3,7,3));//lo w
splice(数组进行删除,添加,替换等操作)
【1】删除(第一个参数为第一项位置,第二个参数为要删除几个。)
【2】添加(第一个参数(插入位置),第二个参数(0),第三个参数(插入的项)。)
【3】替换(第一个参数(起始位置),第二个参数(删除的项数),第三个参数(插入任意数量的项)。)
(4)字符串大小写转换
s1="hello"
s1.toLowerCase() //转换为小写
s1.toUpperCase() //转换为大写
(5)去空格
s1=" he llo "
s1.trim() //去字符串前后的空格
(6)split 分割字符串
s1="he,l,lo,wo,r,d"
console.log(s1.split(","));//[he,l,lo,wo,r,d]
console.log(s1.split(",",2));//[he,l]
s2="heollolw"
console.log(s2.split("ol"));//he l w
(7)字符串位置方法 返回指定字符串的第一个位置,如果找不到,返回-1
第二个参数表示查找的起始位置
indexOf()
lastIndexOf() 从后向前查找
s1="hello world"
s1.indexOf("e") //1
s1.indexOf("o") //4
s1.indexOf("m") //-1
s1.indexOf("o",6) //7 表示从第六个开始找
s1.lastIndex("o")
s1.lastIndex("l")
(8)替换replace
[1]返回新的字符串
[2]只替换第一个匹配项
s1="hello"
s1.replace("e","m")
s1.replace("l","m") //hemlo
var s1="hello"
while(s1.indexOf("l")>-1){
s1= s1.replace("l","m");
}
console.log(s1);//hommo
s2="vbnmghj" 将所有a替换成m
// 正则表达式;i:忽略大小写;g:全局查找
reg=/a/ig
s3=s2.replace(reg,"m")
二、常用ASCII码
a 97
z 122
A 65
Z 90
0 48
9 57
空格 32
回车 13