基本简介:
- 在JS中,字符串中的索引无论大小写(中文也只代表了一个字符)。
- search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果没有找到任何匹配的子串,则返回 -1。
- test() 方法用于检索字符串中指定的值。返回 true 或 false。
字符串的截取:
//字符串截取
var newstr = str.substr(6, 6);//截取多少长度
var substrs = str.substring(6, 12);//substring不包含最后的索引值
利用正则表达式进行字符串分隔:
var strlist = "公牛#鲁宁%牌牌琦|牛逼";
//配合正则表达式进行分隔字符串
var newstr = strlist.split(/\||#|%/);//使用正则分割多个字符
//var newstr = strlist.split(/\||#|%/);//返回的是一个数组
alert(newstr);
//-------------------------------------------------------------------
//字符串分割
newlist=strlist.split('|',2);//限定返回分割之后的元素数组个数
JS中Date和Math对象:
var d = new Date();
console.log(d.getFullYear());
console.log(d.getMonth());//浏览器控制台显示数据 (索引从0表示1月) 月份使用索引显示八月显示7
console.log(d.getDate());//日期
console.log(d.getHours());
console.log(d.getTime());//返回毫秒数
alert(Math.abs(-2));//绝对值
alert(Math.floor(23.5));//向下取整
alert(Math.ceil(23.5));//向上取整
alert(Math.max(21, 22, 27, 25));//最大值(不能放数组) 只能放整数
alert(Math.min(12, 45, 21, 13));//最小值
alert(Math.PI);//圆周率
alert(parseInt(Math.PI * (12 * 12)));
字符串相关使用实例:
var strlist = "我爱北京天安门,天安门上太阳升。我爱北京天安门,天安门上太阳升。我爱北京天安门,天安门上太阳升。"+
+"我爱北京天安门,天安门上太阳升。我爱北京天安门,天安门上太阳升。我爱北京天安门,天安门上太阳升。)";
//查询每个天安门,并输出第几个并输出所在索引位置
//先定义要使用的变量
var keyworlds = "天安门", indexno = 0, counts = 0;
//查找不找返回-1,不停寻找
while ((indexno = strlist.indexOf(keyworlds, indexno)) != -1) {
counts++;
alert(keyworlds + "出现第" + counts + "的位置是:" + indexno);
//为查找的起始索引重新赋值
indexno += 3;
}