<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>String类型</title>
</head>
<body>
<script type="text/javascript">
/*
1、在JS当中字符串使用双引号或单引号括起来。比如:"abc",'abc'.
2、在JS当中如何创建字符串:
第一种方式:var x = "abc"; 使用typeof x 获取到的数据类型是string 称为小string
第二种方式:var y = new String("abc"); 使用typeof y 获取到object,称为大String
3、无论是小string还是大String,他们的属性和函数都是通用的。
4、关于String类型的常用属性和函数:
常用属性:length 获取字符串长度
常用函数:indexof 获取指定字符串在当前字符串中第一次出现处的索引
lastIndexof 获取指定字符串在当前字符串中最后一次出现处的索引
replace 替换
substr 截取子字符串
substring 截取子字符串
tolowerCase 转为小写
toupperCase 转为大写
split 拆分字符串
*/
var x = "abc";
alert(typeof x);//string
var y = new String("jack");
alert(typeof y);//object
//获取字符串长度
alert(x.length);//3
alert(y.length);//4
alert("http://www.baidu.com".indexOf("http"));//0
alert("http://www.baidu.com".indexOf("https"));//-1
//判断一个字符串是否包含某个子字符串
alert("http://www.baidu.com".indexOf("https") >= 0 ? "包含" : "不包含");//不包含
//使用&替换字符串中的% 只替换了一个%,如果需要全部替换需要使用正则表达式。
alert("name=value%name=value%name=value".replace("%","&"));//name=value&name=value%name=value
/*
注意下面两个方法的区别:
1、substr(startIndex,length);开始下标,长度
2、substring(startIndex,endIndex);包含开始下标,不包含结束下标
*/
alert("abcdefgh".substr(2,4));//cdef
alert("abcdefgh".substring(2,4))//cd
</script>
</body>
</html>
JavaScript中的String类型
于 2023-02-02 08:55:27 首次发布