字符串操作常用方法总结

String 类型提供了很多方法,用于辅助完成对 ECMAScript 中字符串的解析和操作。

1、字符方法

两个用于访问字符串中特定字符的方法是:chatAt()和chatCodeAt()和stringValue[],这两个方法都接受一个参数,既基于0的字符位置。chatAt()) 方法以单字符字符串的形式返回给定位置的那个字符。例如:

var atr= "hello world";
console.log(atr.charAt(1));//e  字符串 "hello world" 位置 1 处的字符是 "e" 
console.log(atr.charCodeAt(1));//101   小写字母 "e" 的字符编码
console.log(atr.stringValue[1]);//e

 2、字符串操作方法

concat()用于将一个或者多个字符串拼接,返回一个新的字符串【一般都是采用+号来拼接字符串,比较简单】

var stringValue = "hello";
var result = stringValue.concat("world");//hello world
console.log(result);hello 不修改原有的字符串

3、基于子字符创创建新字符串的方法:slice(),sbuString(),sbustr()

slice(),sbuString()接受两个参数,第一个参数是指定子字符串的起始位置,第二个参数是最后一个字符的位置(返回值不包括结束位置的内容)

substr()接受两个参数,第一个参数是指定子字符串的起始位置,第二个参数指定的是指定返回的个数。如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。例如:

var stringValue = "hello world";
console.log(stringValue.slice(3))//lo world
console.log(stringValue.substring(3));//lo world
console.log(stringValue.substr(3));//lo world
console.log(stringValue.slice(2,4));//ll
console.log(stringValue.substring(2,4));//ll
console.log(stringValue.substr(2,4));//ll0 w

 4、字符串位置方法,indexOf()和lastIndexOf()indexOf()和lastIndexOf()的区别

4.1 indexOf()从字符串的开头向后搜索,lastIndexOf()是从字符串的末尾向前搜索

4.2 这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。换句话说,
indexOf() 会从该参数指定的位置向后搜索,忽略该位置之前的所有字符;而 lastIndexOf() 则会从
指定的位置向前搜索,忽略该位置之后的所有字符。【不论是向前搜索还是向后搜索,返回的数值始终是从前开始往后数的】

例如:

var stringValue = "hello world";
console.log(stringValue.indexOf("o"));//4
console.log(stringValue.lastIndexOf("o"));//7
console.log(stringValue.indexOf("o",6));//7
console.log(stringValue.lastIndexOf("o",5))//7

 

猜你喜欢

转载自boyp.iteye.com/blog/2342266