美文网首页
02.11 字符串

02.11 字符串

作者: xxxQinli | 来源:发表于2019-02-11 18:39 被阅读0次

    字符串运算

    • a. 加法运算
      var str1 = 'abc';
      var str2 = 'hello';
      console.log(str1+str2) //abchello
      console.log(str1+100) //abc100
      console.log(str1+[1,2,3]) //abc1,2,3
    • b.比较运算:> < == === != !==
      // 1. 比较相等
      console.log('abc' == 'abc'); //true
      console.log('abc' == 'bac'); //false
      console.log(100 == '100') ; //true
      console.log(100==='100'); //false

    比较大小:和python字符串比较大小的方式一样

    • console.log('abc' > 'bd'); //false
    • console.log('z' > 'sh'); //true

    字符串长度

    console.log(str2.length);
    var str3 = new String('abc');
    console.log(str3);
    var newStr = str3.big();
    console.log(newStr);
    

    charAt(index) 获取下标对应的字符

    console.log('hello'.charAt(0));
    

    charCodeAt(index)

    获取下标对应的的编码(JS中的字符也是采用的unicode的编码)
    console.log('hello'.charCodeAt(0));
    

    concat(str1, str2, str3) 将字符串连接上去

    将字符串和多个数据依次连接在一起产生一个新的字符串(相当于+的功能)
    console.log('hello'.concat('abc', 'aaa')); 
    

    endWidth(str) 判断字符串1是否以字符串2结尾

    console.log('hello'.endsWith('llo'));
    

    str.indexOf(str) 获取字符串出现的下标位置

    console.log('hello'.indexOf('l'));
    

    str.lastIndexOf(str) 获取最后一次出现的位置

    console.log('hello'.lastIndexOf('l'));
    

    str.match(正则表达式) 相当于python中re模块中的match

    var re_str = /\d{3}$/;
    var result = '237'.match(re_str);
    console.log( result,result[0], result['input']); 
    

    repeat(num) 重复次数,相当于python中的乘

    var str4 = 'abc';
    console.log(str4.repeat(4));
    

    replace(rgexp, newstr) 只替换满足正则表达式条件的第一个字符串

    console.log('adadada'.replace(/\w/, 'x'));
    

    slice(startnum, endnum)

    console.log('hello'.slice(0, 2));
    console.log('hello'.slice(-3, -1));
    

    split 字符串分割成数组

    console.log('hello'.split('e'))
    console.log('abc'.repeat(4));

    相关文章

      网友评论

          本文标题:02.11 字符串

          本文链接:https://www.haomeiwen.com/subject/iatceqtx.html