• string的一些操作,类似数组


    1.串的切割

    var a="hello world";//a.length=11
    alert(a.slice(3));
    alert(a.substring(3));
    alert(a.substr(3));//三个都lo world

    alert(a.slice(3,7));//3到7
    alert(a.substring(3,7));//3~7
    alert(a.substr(3,7))//3后面7个字符

    alert(a.slice(-3));//a.length-3开始,11-3=8="rld";
    alert(a.substring(-3));//substr会当作是0,hello world;
    alert(a.substr(-3));//和slice模式一样

    alert(a.slice(3,-4));//(3,a.length(11-4=7))lo w
    alert(a.substring(3,-4));//当作(3,0),又有自己调整为(0,3)的特性,hel
    alert(a.substr(+3,-4));//也会当作(3,0),后面参数为0 自然就是“”(空串)

    2 string indexOf

    var a="hello world);

    a.indexOf("o");//4

    a.lastIndexOf("0");//7

    a.indexOf("o",6)//在第6个开始

    a.lastIndexOf("o",6)

    3.trim()删除空格

    4.toLowerCase()大小写

     toUpperCase()

    5.串里面查找

    1)match()和RegExp一样

    var a="hello world";
    var b=/lo/;
    var c=a.match(b);
    console.log(c[0],c.index,c.lastIndex);

    2)search()只返回第一的位置,像c.index

    var a="hello world";
    var b=/lo/;
    var c=a.search(b);
    console.log(c[0],c.index,c.lastIndex);//三个都是undefined
    console.log(c);

    6 串的方便替换

    var a="cat,bat,fat,dat";
    var b=a.replace(/at/g,"fuck");
    console.log(b);

    第二个参数还可以加段编码,更新匹配结果

    var a="cat,bat,fat,dat";
    var b=a.replace(/(.at)/g,"fuck($2)");

    还可以是个函数function(match,pos,originalText)分别是模式的匹配项,匹配项在字符串的位置,原始字符(前面的match)

    var a="<000<0.00<>0<.0";
    var b=a.replace(/[<>.]/g,function (match,pos,originalText) {
    switch(match){
    case "<":
    case ">":
    return "1";
    case ".":
    return originalText;//<>.这些
    }
    });
    console.log(b);

    7串化为数组

    var a="sdds,sf,we,zc";
    var b=a.split(",");
    var c=a.split(/[/,]/);
    console.log(b,c);

    8串的比较

    var a="fuck";
    var b="e";
    console.log(a.localeCompare(b));//不能直接减

    9 fromCharCode()方法

    String.fromCharCode(104,101,108,108,111));编码转换为字符hello

  • 相关阅读:
    一个程序员的职业规划
    基于Andoird 4.2.2的Account Manager源代码分析学习:创建选定类型的系统帐号
    [置顶] C++学习书单
    js快速分享代码
    The declared package does not match the expected package
    IBM Rational Appscan Part 1
    IBM Rational Appscan: Part 2 ---reference
    阅读redis源代码的一些体会
    18 Command Line Tools to Monitor Linux Performance
    代码规范
  • 原文地址:https://www.cnblogs.com/vhyc/p/5767142.html
Copyright © 2020-2023  润新知