字符方法 charAt()和charCodeAt() String.fromCharCode()
在做编程题目的时候,如果发现自己忘记了数字或者是字符的charCode,可以用字符方法获取。这样就不用记住了。
str= 'abc'
"abc"
str[0].charAt()
"a"
str[0].charCodeAt()
97
String.fromCharCode() 通过字符编码来获取字符
String.fromCharCode(97)
"a"
'a'.charCodeAt()
97
字符串操作
concat
连接字符串的方法 不会改变原来的字符串,会生成一个新的字符串
str
"abc"
str2 = '111'
"111"
str.concat(str2,str)
"abc111abc"
基于子串的操作 slice like substring [substr 很独特 ]
- substring(a,b) 截取下标[a,b)的子串 2个参数都是下标 下标可以互换位置 不可以是负数
str = '0123456789'
"0123456789"
str.substring(0,1)
"0"
str.substring(0,2)
"01"
str.substring(2,0)
"01"
str.substring(-4,-1)
""
- substr(a,b) 从下标为 a开始,连续截取长度为b的子串 只有一个下标 一个截取字符的个数 下标可以为负数 独特
- slice(a,b)
str
"0123456789"
str.slice(3,3) // 都是下标 没有长度 这一点和substring是一致的
""
str.slice(0,3)
"012"
str.slice(3,0) // 不可以改变参数的位置 和substring的区别所在
""
str.slice(-4,-2) // 可以传负数 和substring的区别所在
"67"
字符串的位置 indexOf() / lastIndexOf()
字符串的位置方法:indexOf()和lastIndexOf()。这两个方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置,没有找到,返回-1.indexOf()从字符串的开头向后搜索子字符串,而lastIndexOf()从字符串的末尾向前搜索子字符串。
如果没有重复元素,两个方法查找的结果一样,都是在自己的查找方向上第一次出现的下标
str
"0123456789"
str.indexOf('a')
-1
str.indexOf('4') // 从前向后找
4
str.lastIndexOf('4') //从后向前找
4
str.lastIndexOf('1')
1
存在重复元素时
str = '123456654321'
"123456654321"
str.indexOf('1')
0
str.lastIndexOf('1')
11
去空格 头尾都去
a = ' 12 '
" 12 "
a.trim()
"12"
字符串匹配
match(),replace(),search(),replace()以及split()方法是String类型定义的集中用于在字符串中匹配模式的几种方法。
match方法只接收一个参数,要么是一个正则表达式,要么是一个RegExp对象。在字符串上调用match()方法,本质上和调用RegExp的exec()方法相同,返回的是一个数组
match
var str = "we are weamy";
var pattern = /we/;
var matches = str.match(pattern);
undefined
matches
["we", index: 0, input: "we are weamy", groups: undefined]
pattern.exec(str)
["we", index: 0, input: "we are weamy", groups: undefined]
替换 replace()
可以将字符串中的指定的内容替换成一个新的内容
参数1:被替换的内容,可以接受一个正则表达式(默认只替换第一次出现的匹配内容,将正则表达式的第二个参数设置为全局匹配模式,可以替换所有符合条件的内容)
参数2:新的内容
str
"cat, fat, sat, bat"
str.replace('at','*')
"c*, fat, sat, bat"
str
"cat, fat, sat, bat"
str.replace('/at/g','*') // 正则表达式不能加‘’
"cat, fat, sat, bat"
str.replace(/at/g,'*') // 正则表达式 的全局匹配
"c*, f*, s*, b*"
搜索
可以搜索字符串中是否含有指定指定的内容,并返回第一次出现的索引
可以接受正则表达式,但是即使将正则表达式的第二参数设置为全局匹配,也只会返回第一次出现的索引
str
"cat, fat, sat, bat"
str.search('bat')
15
str.search('batt')
-1
str.search('at')
1