1. 程式人生 > >第40天:字符串操作:截取字符串

第40天:字符串操作:截取字符串

uppercase 若是 sun 格式 ctype ntb 位置 str 字符

1、slice()
slice("取字符串的起始位置",[結束位置]);//初始位置一定要有,結束位置可有可無
var txt="abcedf";
txt.slice(3);//從txt裏面字符的第3(索引號)個開始取,一直到最後
txt.slice(3,6);//取txt索引號3-6的字符串,不包含6
起始位置可以是負數,若是負數,從字符串右邊向左邊取
txt.slice(-1);

2、substr()
substr(起始位置,[取的個數]);
不寫個數,默認從起始位置到最後
substr(-1);少用,IE6、7、8報錯
substring始終會把小的值作為起始值,較大的作為結束位置
例如:sunstring(6,3),實際中自動變成substring(3,6)

3、保留小數位數

console.log(str.substr(0,str.indexOf(".")+3));//保留小數點後2位
console.log(parseInt(PI*100)/100);//先乘100取整,再除100
console.log(PI.toFixed(2));//直接使用toFixed()方法

案例:

1、保留小數位數

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>保留小數位數</title>
6 </head> 7 <body> 8 9 </body> 10 <script> 11 var PI=3.141592654;//常量大寫 12 var str=PI+"";//數字轉換為字符串,再操作 13 //var index=str.indexOf(".");//返回小數點的位置 14 //console.log(str.substr(0,index+3));//保留小數點後2位 15 console.log(str.substr(0,str.indexOf(".")+3));//保留小數點後2位,3.14 16 console.log(parseInt(PI
*100)/100);//先乘100取整,再除100,3.14 17 console.log(PI.toFixed(2));//直接使用toFixed()方法,3.14 18 </script> 19 </html>

2、驗證文件格式是否正確

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>驗證文件格式是否正確</title>
 6 </head>
 7 <body>
 8 <input type="file" id="file"><span></span>
 9 </body>
10 <script>
11     var file=document.getElementById("file");
12     file.onchange=function(){
13         var path=this.value;//得到當前文件路徑
14         var last=path.substr(path.lastIndexOf(".")).toUpperCase();//從後面第一個點開始截取文件後綴名
15         //console.log(last);
16         if(last==".JPG"||last==".PNG"){
17             this.nextSibling.innerHTML="格式正確";
18         }else{
19             alert("文件格式不支持");
20         }
21     }
22 </script>
23 </html>

第40天:字符串操作:截取字符串