学习内容:
一、字符串操作
1.字符串的创建
var s1="hello"
var s2=new String("hello")
2.属性
s1.length 获取字符串的长度
3.方法
(1)获取字符的方法
charAt() 返回给定位置的字符
charCodeAt() 返回字符编码
[] var s1="hello"
01234----索引/下标值
console.log(s1[1]) //e
console.log(s1[0]) //h
console.log(s1[-1]) //undefined error
(2)拼接字符串
+ : 字符串的连接
concat() :用于将一个或多个字符串拼接起来,并返回 拼接后得到的新字符串
var s1="hello"
var s2=s1.concat("world")
var s2=s1.concat("world","student","!")
console.log(s2)
(3)子字符串
substr(起始位置,长度) 从起始位置截取指定长度的子字符串
如起始位置为负数,则倒数
console.log(s1.substr(3)) //lo world
console.log(s1.substr(3,6)) //lo wor 6为截取的长度
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
substring(起始位置,终止位置) 起始包含,终止不包含,遇到负数会自动转换为0,起始若大于终止,则自动调换
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(起始位置,终止位置) 识别负数
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)) //
(4)字符串大小写转换
s1="heLLo"
s1.toLowercase()
s1.toUppercase()
(5)去空格(去左右空格,中间空格不变)
s1=" he llo "
console.log(s1.trim()) //he llo
(6)split 字符串分割
s1="he,l,lo,wo,r,ld"
console.log(s1.split(",")) //[he,l,lo,wo,r,ld]
console.log(s1.split(",",2)) //[he,l]
s2="heollolw"
console.log(s1.split("o")) //[he,ll,lw]
(7)字符串位置方法
indexOf() 返回指定字符的第一个位置
如找不到返回-1,第二个参数表示查找的起始位置
lastIndexOf() 从后向前查找
s1="hello world"
console.log(s1.indexOf("e")) //1
console.log(s1.indexOf("o")) //4
console.log(s1.indexOf("m")) //-1
console.log(s1.indexOf("o",6)) //7
console.log(s1.lastIndexOf("o")) //7
console.log(s1.lastIndexOf("l")) //9
(8)替换 replace
[1]返回新的字符串
[2]替换第一个匹配项
s1="hello"
console.log(s1.replace("e","m")) //hmllo
console.log(s1.replace("l","m")) //hemlo
二、字符串的删除
(1)replace
//*删除字符串中所有的数字
function f1(n1){
for(var i = 0;i<n1.length;i++){
if(n1.charCodeAt(i)>=49&&n1.charCodeAt(i)<=57){
n1 = n1.replace(n1[i],"")
i=i-1
}
}
alert(n1)
}
f1("he123llo")
(2)删除字符串的第一位 s1.substr(1)
删除字符串的最后一位 s1.substr(0,s1.length-2)
substr
(3)截取字符串的开始和结束
substring
s1.substring(3,s1.length-1)
(4)删除指定的字符
s1="helloworld"
s2=s1.split("o")------[hell,w,rld]
数组中的方法:由数组转字符串 join
s2.join("")-----hellwrld
s2.join("3")----hell3w3rld
2.字符串的比较
(1)localeCompare:调用本地操作系统的排序规则
v1=v2 返回0
v1排在v2之前 返回-1
v1排在v2之后 返回1
3.字符串编码
(1)charCodeAt()
s1="a"
s1.charCodeAt(0) //97
s2="海"
console.log(s2.charCodeAt(0)) //28023
(2)fromCharCode():根据ASCII码或者Unicode码的10进制码进行解析
console.log(String.fromCharCode(65))
console.log(String.fromCharCode(28023))
(3)escape() ---输出Unicode码
unescape()--根据Unicode码输出字符
var s1="海"
console.log(escape(s1)) //\u6D77
console.log(unescape("\u6D77"))