zoukankan      html  css  js  c++  java
  • js 常用字符串操作

     var str='hello word';
    //查找字符串索引为1的字符
    console.log(str[1]);//返回e //这样早期版本浏览器不支持 如IE7
    console.log(str.charAt(1));//返回e 浏览器兼容
    //查找字符串索引为1的字符编码
    console.log(str.charCodeAt(1));//返回101 e的字符编码
    //查抄字符串所在索引的位置
    console.log(str.indexOf('o'));// 字符串开头开始检测,返回4 没找到返回-1
    console.log(str.lastIndexOf('o'));//字符串结尾开始检测返回7 没找到返回-1

    //字符串截取str.slice(start,end)
    console.log(str.slice(1,4));
    //返回‘ell’ 第一个参数start开始截取字符串的索引1为第二个(0,1)是‘e’
    // end为4 注意 end 本身是不在截取范围之内 也就是‘o’之前的截取 本身不截取
    //如end 省略 截取直到末尾
    // 如 start end 为负数 则截取末尾开始 相当于加上这个字符串的length
    console.log(str.slice(-4,-2));//返回 wo
    console.log(str.slice(-4+str.length,-2+str.length));//返回 wo

    //substring()与str.slice()基本相同 只不过参数为负数时 substring 自动转换为0 而且将较小的参数设置为起始位置
    console.log(str.substring(1,4));///返回‘ell’与str.slice()相同
    console.log(str.substring(2,-5));///返回‘he’与str.slice()不同 -5 转换为0 而且将较小的参数设置为起始位置 相当于str.substring(0,2)

    //substr 第一个参数开始索引与str.slice相同,可以是负数 第二个参数为截取总长度, 第二个参数如果为0和负数,截取不到字符串
    console.log(str.substr(1,4));///返回‘ello’
    //console.log(str.substring(2,-5));

    //字符串转换数组
    var str='2010/10/11';
    var arr=str.split('/'); //参数为字符串分隔符
    console.log(arr);//返回["2010", "10", "11"]

    //字符串替换

    var str='她是2b';
    var newstr=str.replace('她','他');
    console.log(str,newstr);//她是2b 他是2b 注replace()不改变原字符串 返回替换后新字符串

    //转换大小写
    var str='hello word';
    var toUpStr=str.toUpperCase();//转换为大写
    var toLowStr=str.toLowerCase(); // 转换为小写
    console.log(toUpStr,toLowStr); //HELLO WORD hello word 注两种方法不改变原字符 返回新字符串
  • 相关阅读:
    Oracle基础知识整理
    linux下yum安装redis以及使用
    mybatis 学习四 源码分析 mybatis如何执行的一条sql
    mybatis 学习三 mapper xml 配置信息
    mybatis 学习二 conf xml 配置信息
    mybatis 学习一 总体概述
    oracle sql 语句 示例
    jdbc 新认识
    eclipse tomcat 无法加载导入的web项目,There are no resources that can be added or removed from the server. .
    一些常用算法(持续更新)
  • 原文地址:https://www.cnblogs.com/hellozg/p/7196311.html
Copyright © 2011-2022 走看看