JavaScript -基础- 函数与对象(二)String

一、判断数据类型typeof与判断对象类型instanceof

1、typeof

typeof只能判断基础数据类型,无法判断引用数据类型

<script>

    var s="hello"

    var i=8; 

    alert(typeof(s))                       //输出string

    alert(typeof(i))                        //输出number

    var s2=new String("hello2")

    alert(typeof(s2))                     //输出为object,但是不知是那种object

</script>

2、instanceof判断取布尔值,看某个对象是不是某个类型

instanceof

var s2=new String("hello2")

alert(s2 instanceof String)                     //判断s2是不是String ,是则返回True,不是则返回False

二、String对象

1、String对象的两种创建方式

1)var s="hello"

1)var s=new String("hello")

2、String对象属性

1)取长度length

alert(s.length)

2)遍历

for (var i in s){

    console.log(s[i])

}

3、String方法

1)编排方法

document.write(s.italics());  //斜体

document.write(s.bold());    //加粗

2)大小写转换

console.log(s.toUpperCase())

console.log(s.toLowerCase())

3)获取执行字符

console.log(s.charAt(3));   //3按照位置取值

console.log(s.charCodeAt(3));   //3位置上面的字符编码

4)查询字符串

console.log(s.search("l"));      //返回hello字符串中第一个"l"的索引值

console.log(s.charCodeAt(3)[0]);  //返回数组,里面是所有匹配结果

5)replace

console.log(s.replace("E","e"));   //替换 

6)split

console.log(s.split("E"));   //切割

7)concat 连接

console.log(s.concat(" world"));  

8)截取字符串

console.log(s.substr(1,2));    //截取从索引位置1开始的2个长度字符

console.log(s.substring(1,3));    //截取从索引位置1,到索引值3的字符串

console.log(s.slice(1,-3));    //截取,可加负数

原文地址:https://www.cnblogs.com/xibuhaohao/p/10455532.html