ES6小实验-复习字符串

字符串用的很频繁,而它的方法也比较多,因此有必要好好的总结下。

1.字符串观赏方法

  charAt() :访问字符串中的特定字符

var str = "hello world"
console.log(str.charAt(1))//e

  该方法接收一个参数,即基于0的字符位置,

  charCodeAt():访问字符串中的特定字符的字符编码

var str = "hello world"
console.log(str.charCodeAt(1))//101

  该方法和上面方法很像,只是返回的不是字符,而是字符编码

  indexOf():查找字符的位置,可以传第二个参数作为起始位置

var str = "hello world"
console.log(str.indexOf("o"))//4

  lastIndexOf():从字符串尾部开始搜索,可以传第二个参数作为起始位置

var str = "hello world"
console.log(str.lastIndexOf("o"))//7

  match():字符串模式匹配,

var str = "cat,bat,sat,fat"
var pattern = /.at/g
var matches = str.match(pattern)
console.log(matches)//["cat", "bat", "sat", "fat"]

  search():字符串模式匹配,与match不同之处在于它返回的是第一个匹配项的索引

var str = "cat,bat,sat,fat"
var pattern = /.at/g
var matches = str.search(pattern)
console.log(matches)//0

 

2.字符串操作方法 

  concat():将一个或多个字符串拼接起来,原值不变

var str = "hello "
var result = str.concat('world')
console.log(result)//hello world
console.log(str)//hello 

  slice():截取子字符串,对原字符串不影响,第二个参数还是以0位为起点

var str = "hello world"
var result1 = str.slice(3)
var result2 = str.slice(3,7)
console.log(result1)//lo world
console.log(result2)//lo w
console.log(str)// hello world

  substr():截取子字符串,对原字符串不影响,第二个参数是要截取多少位

var str = "hello world"
var result1 = str.substr(3)
var result2 = str.substr(3,7)
console.log(result1)//lo world
console.log(result2)//lo worl
console.log(str)// hello world

  substring():截取子字符串,对原字符串不影响,第二个参数还是以0位为起点,它与slice()的区别在于当第二个参数为负数时,substring()和substr()会把负数变成0来处理,而slice()会把它和总长度相加来处理,这三个很容易混淆

var str = "hello world"
var result1 = str.substring(3,-4)
var result2 = str.substr(3,-4)
var result3 = str.slice(3,-4)
console.log(result1)//hel
console.log(result2)//“”
console.log(result3)// lo w

  trim(): 删除前置及后缀的所有空格,原字符串保持不变

var str = "    hello world    "
console.log(str.trim())//hello world

  toLowerCase(),toUpperCase():字符串大小写转换

var str = "hello world"
console.log(str.toUpperCase())//HELLO WORLD

   replace():第一个参数可以是一个RegExp对象或者一个字符串,第二个参数可以是一个字符串或者一个函数

var str = "cat,bat,sat,fat"
var pattern = /at/g
var result1 = str.replace("at", "ond")
var result2 = str.replace(pattern, "ond")
console.log(result1)//cond,bat,sat,fat
console.log(result2)//cond,bond,sond,fond

  split():基于指定的分隔符将一个字符串分隔成多个字符串,并放在一个数组中

var str = "red,blue,green,yellow"
console.log(str.split(","))//["red", "blue", "green", "yellow"]
console.log(str.split(/[^\,]+/))//["", ",", ",", ",", ""]

 

posted on 2017-04-02 21:18  且歌且行吧  阅读(150)  评论(0编辑  收藏  举报

导航