zoukankan      html  css  js  c++  java
  • String类型(二)

    //String类型
    //字符串位置方法
    console.log("字符串位置方法");
    //indexOf(),lastIndexOf():从一个字符串中搜索给定的子字符串,返回子字符串的位置(没有则返回-1)
    //用法 string.indexOf(str, location):str为子字符串,location为可选参数,表示从哪个位置开始搜索
    //indexOf()默认从开头向后搜索,返回第一个字符串的位置
    //lastIndexOf()默认从末尾向前搜索,返回第一个字符串的位置
    var stringValue = "hello world!";
    
    console.log(stringValue.indexOf("o"));//4 从左向右第一个出现的位置是4
    console.log(stringValue.lastIndexOf("o"));//7 从最后向前,第一个出现的位置是7
    console.log(stringValue.indexOf("o", 5));//7 从5位置向后搜索,第一个出现的位置是7
    console.log(stringValue.lastIndexOf("o", 5));//4 从5位置向前,第一个出现的位置是4
    
    //可巧用一个循环,来匹配所有子字符串出现的位置
    var stringValue2 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
    var positions = [];
    var pos = stringValue2.indexOf("e");
    
    while (pos > -1) {
        positions.push(pos);
        pos = stringValue2.indexOf("e", pos+1);
    }
    console.log(positions);//[3, 24, 32, 35, 52]
    
    //字符串大小写转换
    console.log("字符串大小写转换");
    //toLowerCase()、toLocaleLowerCase()、toUpperCase()和toLocaleUpperCase()
    //一般用toUpperCase()和toLowerCase()
    var stringValue3 = "Hello World!";
    
    console.log(stringValue3.toLocaleUpperCase());//HELLO WORLD!
    console.log(stringValue3.toUpperCase());//HELLO WORLD!
    console.log(stringValue3.toLocaleLowerCase());//hello world!
    console.log(stringValue3.toLowerCase());//hello world!
    
    //字符串的模式匹配方法
    //match()、search()
    //和正则的那个一样,match()返回数组(没有返回null),可以带参数,参数可以为正则表达式,也可以是字符串,search()返回第一次出现的位置(没有则返回-1)
    //用法string.match(regExp) string.search(regExp);
    
    //localeCompare()方法:比较两个字符串,并返回字符串在字母表中应该排在前面还是后面(前面返回负数,一般为-1; 等于返回0; 后面返回正数,一般为1)
    var stringValue4 = "yellow";
    console.log(stringValue4.localeCompare("brick"));//1
    console.log(stringValue4.localeCompare("yellow"));//0
    console.log(stringValue4.localeCompare("zoo"));//-1
    
    //fromCharCode()方法:等于charCodeAt()的相反操作,接收一或多个字符串编码,将他们转换成字符串
    //用法 string.fromCharCode(str)
  • 相关阅读:
    让电脑中的文件后缀显示完整
    [trie][异或] hdu 6625 three arrays
    [全排列] hdu 6628 permutation 1
    [模板][最大流]dinic
    [模板]矩阵十进制快速幂
    CCPC-Wannafly Summer Camp 2019 Day1
    [技巧]ARubbish
    [dp]第十届蓝桥杯国赛CB组C
    [暴力]分块
    [模板]主席树及其应用
  • 原文地址:https://www.cnblogs.com/qiangspecial/p/3131645.html
Copyright © 2011-2022 走看看