一.字符串
代码如下:
var language = "javascript";
var language = 'javascript';
字符串可以使用双引号和单引号,根据个人爱好而定。
字符串具有length属性,可以返回变量中字符串的个数。
代码如下:
var test1 = "teacher" ;
document.write(test1.length);
//输出test1的字符串个数:7
反之,想获取指定位置的字符,可以使用charAt()函数(第一个字符为0,第二个字符为1,依次类推)
代码如下:
var test1 = "teacher" ;
document.write(test1.charAt(1));
//运行结果为:e ,
如果想取得变量中的字符串,可以采用slice(),substring()或者substr()函数。
其中,substring()和slice()都接受两个参数
代码如下:
var test1 = "teacher" ;
document.write(test1.substring(1)+"<br>");// 输出eacher
document.write(test1.substring(1,4)+"<br>"); //输出eac
document.write(test1.slice(1,4)+"<br>"); //输出eac
document.write(test1.slice(4)+"<br>"); //输出her
document.write(test1 + "<br>");//完整字符串
从以上内容看出,substring()和slice()都不改变字符串内容,只返回字符串的内容。
substing()和slice()的区别主要是对负数的处理不同。
负数参数对于slice()而言,从字符串末尾往前计数,对于substring()来说,则是忽略负数,从0开始处理,并将两个参数中较小的数字作为起始位,较大的作为结束位。
例如substring(2,-3)等同于substing(2,0),也就是等同于substring(0,2)。
代码如下:
var test1 = "teacher" ;
document.write(test1.substring(2,-3)+"<br>"); //te
document.write(test1.substring(2,0)+"<br>"); //te
document.write(test1.substring(0,2)+"<br>"); //te
document.write(test1.slice(2,-3)+"<br>"); //ac
document.write(test1 + "<br>"); //teacher
substring()和substr()的区别,举例说明。
代码如下:
var tt,ss ;
var s = "hellobeijing";
tt = s.substring(2,8)+"<br>";
ss = s.substr(2,8);
document.write(tt);//输出:llobeij 输出下标2到下标8之间的字符
document.write(ss); //输出:llobeiji (输出下标2后的8个字符)
对于用法,另一博友有更多实例(地址)
在搜索字符串上,Javascript提供了indexof()和lastindexof()两个函数。
代码如下:
var s = "woaibeijing";
dd = s.indexOf("e")+"<br>";//从前往后
新闻热点
疑难解答
图片精选