String的常用属性

String字符串

<script>
  var s1 = "Hello";
  var s2 = new String('Hello');
  var s3 = String(true);
  console.log(typeof s1); // string
  console.log(typeof s2);// object -字符串对象
  console.log(typeof s3);// string
  
</script>

静态方法

String.fromCharCode()

<script>
  String.fromCharCode(100); // d
  String.fromCharCode(0x20BB7) === String.fromCharCode(0x0BB7); // true
  // 这种现象的根本原因在于,码点大于0xFFFF的字符占用四个字节,而 JavaScript 默认支持两个字节的字符。这种情//况下,必须把0x20BB7拆成两个字符表示。
</script>

实例属性

  • String.prototype.length

  • String.prototype.charAt(下标); 返回字符串对应下标字符,下标超出则为空字符

    <script>
      var s1 = "Hello";
      console.log(s1.charAt(2)); //l
      console.log(s1[2]); // l
    </script>
    
  • String.prototype.charCodeAt(); 返回对应字符的Unicode码点

  • String.prototype.concat(可以为多个字符串); ----- 合并多个字符串

    <script>
      "a".concat('p','ple'); // apple
    //  concat方法将参数先转成字符串再连接,所以返回的是一个三个字符的字符串。
      var one = 1;
      "a".concat(one); // a1
    </script>
    
  • String.prototype.slice(开始下标结束下标[不包含]); - 方法用于从原字符串取出子字符串并返回,不改变原字符串

    <script>
      var s1 = "abcedfg";
    	s1.slice(0,3); // abc
      s1.slice(0); // abcdefg
     	s1.slice(1,-1); // abcedf(将负数下标加上长度length)
    </script>
    
  • String.prototype.substring();

  • String.prototype.substr(开始位置,字符个数);

    <script>
      var s1 = "abcdefg";
      console.log(s1.substr(2,4)); // cdef
      // 如果第一个参数是负数,表示倒数计算的字符位置。
      // 如果第二个参数是负数,将被自动转为0,因此会返回空字符串。
    
    
    </script>
    
  • String.prototype.indexOf(字符串)

    indexOf方法用于确定一个字符串在另一个字符串中第一次出现的位置,返回结果是匹配开始的位置。如果返回-1,就表示不匹配。

    <script>
      var s1 = "abcdefg";
      s1.indexOf("a"); // 0 ---表示字符串"a"在s1中第一次出现的位置为0
    </script>
    
  • String.prototype.lastIndexOf(); 效果与indexOf()一样,从尾部开始匹配

  • String.prototype.trim(); 方法用于去除两端空格,不影响源字符串

  • String.prototype.toLowerCase()

  • String.prototype.toUpperCase();

  • String.prototype.match()

    match方法用于确定原字符串是否匹配某个子字符串,返回一个数组,成员为匹配的第一个字符串。如果没有找到匹配,则返回null

    'cat, bat, sat, fat'.match('at') // ["at"]
    'cat, bat, sat, fat'.match('xt') // null
    

    返回的数组还有index属性和input属性,分别表示匹配字符串开始的位置和原始字符串。

    var matches = 'cat, bat, sat, fat'.match('at');
    matches.index // 1
    matches.input // "cat, bat, sat, fat"
    
  • String.prototype.search(); 返回第一个匹配的位置

  • String.prototype.replace(带替换的字符串,新字符串); 返回替换第一个替换的新的字符串, 源字符串不变

    var s2 = 'cat, bat, sat, fat';
    console.log(s2.replace('a','b')); // cbt, bat, sat, fat
    console.log(s2); // cat, bat, sat, fat
    
  • String.prototype.split()方法按照给定规则分割字符串,返回一个由分割出来的子字符串组成的数组。

  • 方法还可以接受第二个参数,限定返回数组的最大成员数。

    var s2 = "Hello";
    // 如果分割规则为空字符串,则返回数组的成员是原字符串的每一个字符。
    var letters = s2.split("");// [ 'H', 'e', 'l', 'l', 'o' ]
    // 如果省略参数,则返回数组的唯一成员就是原字符串。
    var letter2 = s2.split();
    var letter3 = s3.split("",3); // ['H','e','l']
    
慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
原文地址:https://www.cnblogs.com/rookie123/p/14344290.html