zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    常用的 写代码 的 指令
    boos
    超级搬运工
    那些年,我读过的书籍(读完一本就在此处更新),立贴。
    ExtJs combobox模糊匹配
    整理了一下eclipse 快捷键注释的一份文档
    中国省份按照拼音排序出现的问题以及临时解决方案
    JetBrains WebStorm 安装破解问题
    ExtJs Grid 删除,编辑,查看详细等超链接处理
    ExtJs Panel 滚动条设置
  • 原文地址:https://www.cnblogs.com/vhyc/p/5767142.html
Copyright © 2011-2022 走看看