与数字类似,基本类型String也有一个对应的String 对象,并且提供了很多有用的方法。
示例 1 :
创建字符串对象
与Number类似的,可以通过new String()创建一个String对象
<script> var x = "5"; var y = new String(x); document.write("变量x的值是:"+x); document.write("<br>"); document.write("变量x的类型是:"+(typeof x)); document.write("<br>"); document.write("变量y的值是:"+y); document.write("<br>"); document.write("变量y的类型是:"+(typeof y)); document.write("<br>"); </script>
示例 2 :
字符串长度
属性 length 返回字符串的长度
<script> var y = new String("Hello JavaScript"); document.write("通过.length属性获取字符串'Hello JavaScript'的长度"+y.length); </script>
示例 3 :
返回指定位置的字符
charAt 返回指定位置的字符
charCodeAt 返回指定位置的字符对应的Unicode码
<script> var y = new String("Hello JavaScrpt"); document.write("字符串y的值:"+y); document.write("<br>"); document.write('通过 charAt(0)获取位置0的字符串: '+y.charAt(0)); //返回H document.write("<br>"); document.write('通过 charCodeAt(0)获取位置0的字符的 Unicode码 :'+y.charCodeAt(0)); //返回H对应的Unicode码 72 </script>