一、字符串的创建方式:
1.字面量
var str = "hello";
console.log(str);
2.构造函数
var str = new String("world");
console.log(str);
//构造函数:字符对象,通过new执行字符构造函数得到,虽然长得是对象的外表,但是他还是字符的内心(作为一个正常的字符来使用)
二、字符串方法概括
方法名 | 功能 |
---|---|
replace () | 替换第一个符合的子字符串 |
slice(m,n) | 截取:从索引为m截取到索引为n(不含n) |
substring(m,n) | 截取:从索引为m截取到索引为n(不含n) |
substr(m,n) | 从索引为m开始截取n个子字符串 |
toUpperCase() | 字符串全部转大写 |
toLowerCase() | 字符串全部转小写 |
concat() | 字符串拼接 |
split() | 按照指定自字符,分割字符串,分割成数组 |
charAt() | 根据索引查数据,当前索引没有数据,返回空字符 |
三、方法详解
1.replace()
功能:替换,并只能替换第一个符合的子串
参数:两个,1老的子串,2要替换成的新串
var str = "abcabcqweacnakdjfhqke";
str = str.replace("a","啊");
console.log(str);
//结果:啊bcabcqweacnakdjfhqke ---原字符串未改变
2.slice()
功能:截取:从索引为m截取到索引为n(不含n)
参数:两个,1子字符串开始位置,2子字符串结束位置
var str = "hello world";
var res = str.slice(2,7);//如果省略第二个参数,则表示字符串一直到原字符结束
console.log(res);
//结果:llo w ---原字符串改变 注意:空格代表一个字符
3.substring(m,n)
功能:截取:从索引为m截取到索引为n(不含n)。与slice()用法相似
参数:两个,1子字符串开始位置,2子字符串结束位置
var str = "hello world";
var res = str.slice(2,7); //如果省略第二个参数,则表示字符串一直到原字符结束
console.log(res);
//结果:llo w ---原字符串改变 注意:空格代表一个字符
4.substr(m,n)
功能:截取:从索引为m开始截取n个子字符串
参数:两个,1子字符串开始位置,2截取子字符串的个数
var str = "hello world";
var res = str.substr(2,7); //如果省略第二个参数,则表示字符串一直到原字符结束
console.log(res);
//结果:llo wor ---原字符串改变 注意:空格代表一个字符
5.toUpperCase()
功能:字符串全部转大写
参数:无
var str = "hello world";
var res = str.toUpperCase();
console.log(res);
//结果:HELLO WORLD ---原字符串未改变
6.toLowerCase()
功能:字符串全部转小写
参数:无
var str = "HELLO WORLD";
var res = str.toLowerCase();
console.log(res);
//结果:hello world ---原字符串未改变
7.concat()
功能:两组字符串拼接
参数:无
var str = "hello";
var str2 = "world";
var res = str.concat(str2);
console.log(res);
//结果:helloworld ---原字符串改变
8.split()
功能:按照指定自字符,分割字符串,分割成数组
参数:1个,自定义被分割的字符
var str = "abc-qwe-asd-zxc";
console.log(str);
var res = str.split("-");
console.log(res);
//结果:(4) ["abc", "qwe", "asd", "zxc"] ---原字符串变成数组
9.charAt()
功能:根据索引查数据,当前索引没有数据,返回空字符
参数:一个,索引
var str = "hello world";
var res = str.charAt(6);
var res = str.charAt(20); //如果前索引没有数据,返回空字符
console.log(res);
//结果:w ---原字符串改变