zoukankan      html  css  js  c++  java
  • 第40天:字符串操作:截取字符串

    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>
  • 相关阅读:
    枚举和字符串之间的转换 [转帖]
    escape,encodeURI,encodeURIComponent函数比较[转帖]
    .net中的Provider模式 [转帖]
    ogg转到mp3
    四季养生(樊正伦教授)
    JavaScript高阶之路
    Python初识
    理解error和exception之间的区别(转)
    一些有用的话
    《爱在雨季》片尾曲
  • 原文地址:https://www.cnblogs.com/le220/p/7577554.html
Copyright © 2011-2022 走看看