ECMAScript——基本数据类型之string

在控制台console.dir(String.prototype)一下,发现String.prototype上的方法挺多的,按功能分类大概列举一下常用方法:

var str = "cataway2015";

1、charAt(index):通过索引index获取指定位置的字符
console.log(str.charAt(3)); -->"a"
charCodeAt(index):通过索引index获取指定位置的字符对应的Unicode编码值
console.log(str.charCodeAt(3)); -->"a"对应的Unicode值97
2、截取字符串
substr(n,m):从索引n开始截取m个字符
console.log(str.substr(3,5)); -->"away2"

substring(n,m):从索引n开始截取到索引m处(不包含m)
console.log(str.substring(3,10)); -->"away201"

slice(n,m):从索引n开始截取到索引m处(不包含m)
console.log(str.slice(3,10)); -->"fengpei"

如果只写n不写m,从索引n开始找到末尾

slice支持负数作为索引
console.log(str.slice(-4));//index=str.length-4
console.log(str.substring(-4));

3、通过制定的字符获取索引
str.indexOf("字符") 获取字符在字符串中第一次出现位置的索引
str.lastIndexOf("字符") 获取字符在字符串中最后一次出现位置的索引
console.log(str.indexOf("a")); -->1
console.log(str.lastIndexOf("a")); -->5
console.log(str.indexOf("2015")); -->7
特殊作用:可以判断字符串中是否包含某一个字符,包含返回索引,不包含返回-1
if(str.indexOf("2015")>-1){
//包含
}else{
//不包含
}

var str = "cataway2015";
4、大小写转换
console.log(str.toUpperCase());//字母转大写
console.log(str.toLowerCase());//字母转小写

5、和数组中join对应的方法--> split:按照指定的字符,把字符串拆分成数组
var str="cat away 2015"

console.log(str.split(" "));//["cat", "away", "2015"]


6、replace(old,new):将老字符替换成新的字符
console.log(str.replace("cat","猫")); -->"猫away2015"

在不使用正则的情况下,一次replace执行只能替换一次
var str = "13/01/25"
console.log(str.replace("/",":").replace("/",":"));
console.log(str.replace(///g, ":")); //正则方式


字符串拼接规则:
原文地址:https://www.cnblogs.com/cataway/p/4964518.html