JavaScript-有关String

7次阅读

共计 1881 个字符,预计需要花费 5 分钟才能阅读完成。

原型方法

  • charCodeAt()、fromCharCode()

    let str = 'hello world';
    str.charCodeAt(); // 104
    // 注意:fromCharCode()是对象属性
    String.fromCharCode(104); // 'h'
  • toLowerCase()、toUpperCase()

    let str = 'Hello World';
    str.toLowerCase(); // 'hello world'
    str.toUpperCase(); // 'HELLO WORLD'
  • indexOf()、lastIndexOf()

    let str = 'hello world';
    str.indexOf('o'); // 4
    str.lastIndexOf('o'); // 7
    str.indexOf('world'); // 6
    str.lastIndexOf('world'); // 6
  • search()

    let str = 'hello world';
    str.search('world'); // 6
    str.search(/world/); // 6
  • replace()

    let str = 'hello world';
    str.replace('world', 'javascript'); // 'hello javascript'
  • repeat()

    let str = 'hello world';
    str.repeat(2); // 'hello worldhello world'
  • includes()

    let str = 'hello world';
    str.includes('a'); // false
    str.includes('world'); // true
  • endsWith()

    let str = 'hello world';
    str.endsWith(''); // true
    str.endsWith(' '); // false
    str.endsWith('world'); // true
  • startsWith()

    let str = 'hello world';
    str.startsWith(''); // true
    str.startsWith(' '); // false
    str.startsWith('hello'); // true
  • concat()

    let str = 'hello';
    str.concat('world'); // 'hello world' 
  • slice()

    let str = 'hello world';
    str.slice(1); // 'ello world'
    str.slice(1,6); // 'ello'
  • split()

    let str = 'hello world';
    str.split(''); // ['hello','world']
  • substr()

    let str = 'hello world';
    // 从起始索引号开始取指定数目
    str.substr(2,3); // 'llo'
  • substring()

    let str = 'hello world';
    // 从起始索引号开始取到结束索引号(前闭后开)
    str.substring(2,5); // 'llo'

Tips

  • search()indexOf()

相同点: 都是找目标参数的 index

不同点: search()支持正则表达式查找

  • substring()slice()

相同点:
都是按照起始 index 和结束 index 取字符串的片段

不同点:
1. slice()的索引支持负数,实际结果是 index+length; substring()的索引也支持负数,但 实际结果是 0
2. substring()的两个参数不用分顺序,永远会把小的 index 放前面;slice()的两个参数严格遵循前后顺序

  let str = 'hello world';
  //length 是 11,- 1 相当于(-1+11)=10
  str.slice(-1); // 'd'
  str.slice(-1,5); // ''str.slice(5,-1); //' worl'str.substring(1,5); //'ello'str.substring(5,1); //'ello'str.substring(-1,5); //'hello'
  • 以上所有原型方法都不会改变字符串本身

对象属性

  • fromCharCode()

    String.fromCharCode(77); // 'M'
    // 不能识别大于 0xFFFF 的码点
    String.fromCharCode(0x20BB7); // "ஷ"
  • fromCodePoint()

    String.fromCodePoint(); // 'M' 
    // 可以识别大于 0xFFFF 的码点
    String.fromCodePoint(0x20BB7); // "????"
正文完
 0