js-基本包装类型:字符串操作与功能实现-干货

1 字符方法

string[index]  访问字符串中特定的字符

chatAt(index) 以单字符字符串形式返回特定位置的字符 'hello'.chatAt(1) 'e'

chatCodeAt(index) 返回那个位置字符的字符编码(二进制字符串形式)

2 字符串操作方法 

  拼接: concat() 

     截取并返回截取字符串 : slice() substr() substring() 

 

concat() 专门用来拼接字符串,但实际中“+”使用的更频繁

基于子字符串创建新字符串,都接收一个或两个参数

slice() 截取字符串不包括第二个参数位 slice(1,3) 截取 12

substr() 第二个参数指定返回的字符个数

substring() 截取字符串不包括第二个参数位 slice(1,3) 截取 12

  一个参数为正 第二个参数为正 第一个参数为负 第二个参数位负
slice 开始位 截取到第二个参数前一位 负数+字符串长度 负数+字符串长度
substring 开始位 截取到第二个参数前一位 所有负值参数都转为0 转换为0
substr 开始位 截取的位数 将负的第一个参数+字符串长度  第二个负变为0

 

 

 

总结:

只有一个参数且为正时 开始位置

只有一个参数且为负时 slice  substr 负数+字符长度 substring转换为0

第二个参数也为负时 slice 负数+字符串长度 substring substr 第二个参数转换为0

var str = 'hello world';

console.log( str.slice(-3) ); // 'rld' 即 slice(-3+11)
console.log( str.substring(-3) ); // 'hello world' 即substring(0)
console.log( str.substr(-3) ); // 'rld' 即 substr(-3+11)
console.log( str.slice(3, -4) ); // 'lo w' 即 slice(3, -4+11)
console.log( str.substring(3, -4) ); // 'hel' 即 substring(3,0)
console.log( str.substr(3, -4) ); // '' 即 str.substr(3,0)

 

3 字符串位置方法

  indexof() 向前搜索返回给定字符串的位置,没有返回-1,第二个参数为开始位置

  lastIndexOf()  向后搜索,第二个参数为开始位置

  trim() 创建一个字符串的副本,删除前置及后缀的所有空格,然后返回结果

 

4 字符串大小写转换方法

  经典 toLowerCase() toUpperCase()

     针对特定地区 toLocalLowerCase() toLocalUpperCase()

5 字符的匹配模式

  match() // 返回一个数组 详情参考正则表达式

  search() // 返回字符中第一个匹配项的索引 详情参考正则表达式

  replace() // 替换 将匹配的字符串替换 详情参考正则表达式

  split() // 指定分隔符,结果为分隔后组成的数组

6 两个字符串比较 localeCompare()  a.localeCompare(b)

    a字符在b之后 返回正数 1

    a和b 是同一个字符 返回0

    a在b之前 -1

7 fromCharCode() 将字符编码转换为字符串,与charCodeAt()相关相反  

  

posted @ 2017-05-02 18:15  Jesonhu  阅读(109)  评论(0编辑  收藏  举报
Top