String()为构造函数,用于字符的类型的转换和字符串操作。
1.所有东西都能往里塞,并转换成字符类型。
var str = String(123);
console.log(str);//123
var str = String('hello world');//hello world
console.log(str);
var str = String(true);
console.log(str);
var str = String(null);
console.log(str);//null
var str = String(undefined);
console.log(str);//undefined
var str = String({});
console.log(str);// [object Object]
var str = String([123]);
console.log(str);//123
2.String()让字符具有Array的特性
var str = new String('hello world');
console.log(str);
返回:
for(var i = 0; i < str.length; i++){
console.log(str[i]);
}
返回
}
2.String()的函数
2.1 indexOf()/lastindexOf()
var str = new String(‘hello world’);
console.log(str.indexOf(‘r’));//8,lastIndexOf()从右边数起,返回右边第一个位置,如果找不到返回-1;
2.2 charAt()输入字符串位置,返回字符串
var str = new String('hello world');
console.log(str.charAt(6));//w
2.3 substring(x,y);截取一段字符,x为起始位置,y为终止位置,但不包括y,该函数命名不遵守小驼峰命名规则
var str = new String('hello world');
console.log(str.substring(0,5));//hello
2.4 replace(‘x’,‘y’),用’y’代替’x’;
var str = new String('hello world');
console.log(str.replace('l','Y'));//heYlo world;只替代左边数起第一个字符,
//若想全部替换需要正则表达式(严格规格表达式)
console.log(str.replace(/l/g,'Y'));//heYYo worYd——g为golbal全部的意思。
2.5 split()将字符串转化为数组
var str = new String('hello world');
console.log(str.split(''));//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]