这篇博客这要是string的基本操作,底下这份文件是我看完一个视频教程(需FQ)的练习。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"/> 5 <title>This is us</title> 6 </head> 7 <body> 8 <p>This file is all about different operations on string object</p> 9 <p>As it‘s an object,we discuss about two things:property and method</p> 10 <p>Property:length</p> 11 <p>method:<li>indexOf() and lastIndexOf()</li> 12 <li>substr() and substring</li> 13 <li>toUpperCase() and toLowerCase</li> 14 <li>replace()</li></p> 15 <script type="text/javascript"> 16 (function(){ 17 //2015 4 28 aftenoon 18 //One property of string is length. Note:This length includes blank space and punctuation(标点符号). 19 //The Two Methods Of The String Variable :1.indexOf(); 2.lastIndexOf(); 20 //Both of the two methods is used to find the index of a string or a series of characters 21 var a="This is a string.", 22 c=a.indexOf("is"),// 2 The index of a series is the index of the first letter,in this case it‘s ‘i‘ 23 b=a.indexOf("is",c+1),// search after the first "is" is skiped(c+1) 24 d=a.lastIndexOf("is"),// 5 25 f=a.lastIndexOf("is",d-1);// search backwards from index 4(5-1),so that the second "is" is skiped 26 alert(a.length); 27 alert(f); 28 //To get a substring in a string use the method substr(); 29 var g=a.substr(0,4);//The first paremeter stands for the index of the first character you want to search for,the second one is the length of that word.In this case,it‘s gonna be the word "this" 30 var h=a.substr(a.indexOf("st"),6);//get the word ‘string’ 31 var i=a.substring(0,4);//This is another way of get the substring but this 4 here does not mean the length of the string,it‘s the end index of the string plus 1,in this case,it‘s 3+1 32 alert(g); 33 alert(i); 34 //Now we can turn the string into all upper case or all lower case using the method toUpperCase() and toLowerCase() 35 var j=a.toUpperCase(); 36 alert(j); 37 var k=a.toLowerCase(); 38 alert(k); 39 //We can also replace a substring with another one using the method replace(); 40 var l=a.replace("string","new life");//change the substring ‘string‘ into ‘new life‘ 41 alert(a); 42 alert(l); 43 }()) 44 </script> 45 </body> 46 </html>
文件的注释已经很详细了,主要就是string这个object的一个length属性(用于拿到这个string中所有的字符数)和几个method。indexOf()和lastIndexOf()用于拿到某个字符的index,用substr()或substring()拿到一个substring,toUpperCase()和toLowerCase()就很简单了,用于把所有字符变成大写或小写。细节在代码中有详细注释,So I Guess That‘s Pretty Much Of It!
对了,你可能对<script></script>之间的(function(){ }())有点蛋疼,这个结构主要用于排除其他文件的干扰。比如你在文件中引入了其他人写的js文件,那么这个被引入的js文件中有一些函数名或变量名可能与你自己定义的冲突,这时,把你的js代码放到(function(){ }())的curly braces(也就是大括号啦),冲突就会被避免。
时间: 2024-10-09 11:34:44