1.字符串本质
String对象是 JavaScript 原生提供的三个包装对象之一,用来生成字符串对象。
String对象也是JS内置对象中使用频率最高的之一。
2.创建字符串
(1) 字面量(基本数据类型)
var str1 = 'hello';
console.log(typeof(str1));//'hello' string
(2) 构造函数(引用数据(对象)类型)
var str2 = new String('world');
console.log(typeof(str2));//object
3.字符数组(字符串其实是由一个个字符组织起来的字符数组)
(1) // 访问字符串的长度
var str = ‘hello qianfeng!’;
console.log(str.length);// 15
(2) // 遍历字符串中的字符
for( var i=0;i<str.length;i++ ){
console.log(str[i]);//‘hello qianfeng!’
}
4. ascii码
ascii码查询:http://ascii.911cha.com/
数字0:48,字符A:65,字符a:97
5. 字符的常用方法
charAt(index):返回在指定索引位置的字符
charCodeAt(index):返回在指定的位置的字符的 Unicode 编码。
indexOf(字符串,index):返回某个指定的字符串值在字符串中首次出现的位置
lastIndexOf(字符串,index):返回某个指定的字符串值在字符串中最后出现的位置
toLowerCase():把字符串转化为小写
toUpperCase():把字符串转化为大写
substr(start,length):从起始索引号提取字符串中指定数目的字符
substring(start,stop):提取字符串中两个指定的索引号之间的字符
slice(start,end):提取字符串的某个部分,并返回提取到的新字符串
split(separator,limit):把字符串分割为字符串数组
fromCharCode():将字符编码转换为字符串,静态方法
trim():会从一个字符串的两端删除空白字符。
//示例
var str1 = '哈呵heLLo world';
charAt(index):返回在指定索引位置的字符
console.log( str1.charAt(4) );// 'o'
console.log( str1[4] );// 'o'
charCodeAt(index):返回在指定的位置的字符的 Unicode 编码。
console.log( str1.charCodeAt(0) );
console.log( str1.charCodeAt(1) );
indexOf(字符串,index):返回某个指定的字符串值在字符串中首次出现的位置
var index = str1.indexOf('o',8);
toLowerCase():把字符串转化为小写
toUpperCase():把字符串转化为大写
console.log( str1.toUpperCase() );
console.log( str1.toLowerCase() );
console.log( str1 );