基础4 JS-string类型
String类型




String 类型包含了三个属性和大量的可用内置方法。

String 也包含对象的通用方法,比如valueOf()、toLocaleString()和toString()方法,但这些方法都返回字符串的基本值。

var box = 'Mr.Lee';
alert(box.charAt(1)); //r
alert(box.charCodeAt(1)); //114
alert(box[1]); //r,通过数组方式截取
PS:box[1]在IE 浏览器会显示undefined,所以使用时要注意。

var box = 'Mr.Lee';
alert(box.concat(' is ', ' Teacher ', '!')); //Mr.Lee is Teacher !
alert(box.slice(3)); //Lee
alert(box.slice(3,5)); //Le
alert(box.substring(3)); //Lee
alert(box.substring(3,5)); //Le
alert(box.substr(3)); //Lee
alert(box.substr(3,5)); //Lee
var box = 'Mr.Lee';
alert(box.slice(-3)); //Lee,6+(-3)=3 位开始
alert(box.substring(-3)); //Mr.Lee 负数返回全部
alert(box.substr(-3)); //Lee,6+(-3)=3 位开始
var box = 'Mr.Lee';
alert(box.slice(3, -1)); //Le 6+(-1)=5, (3,5)
alert(box.substring(3, -1)); //Mr. 第二参为负,直接转0,
//并且方法会把较小的数字提前,(0,3)
alert(box.substr(3, -1)); //'' 第二参数为负,直接转0 ,(3,0)
PS:IE 的JavaScript 实现在处理向substr()方法传递负值的情况下存在问题,它会返回原始字符串,使用时要切记。

var box = 'Mr.Lee is Lee';
alert(box.indexOf('L')); //3
alert(box.indexOf('L', 5)); //10
alert(box.lastIndexOf('L')); //10
alert(box.lastIndexOf('L', 5)); //3,从指定的位置向前搜索
PS:如果没有找到想要的字符串,则返回-1。

var box = 'panbiao';
alert(box.toLowerCase()); //全部小写
alert(box.toUpperCase()); //全部大写

var box = 'Mr.Lee is Lee';
alert(box.match('L')); //找到L,返回L 否则返回null
alert(box.search('L')); //找到L 的位置,和indexOf 类型
alert(box.replace('L', 'Q')); //把L 替换成Q
alert(box.split(' ')); //以空格分割成字符串