JS字符串方法和属性

286 阅读4分钟

字符串方法和属性

定义字符串:var str = 'hello', str2 = 'world'

属性

  • length属性:字符串长度
var str = 'hello'
var len = str.length // 5

字符串转数组

  • split()
    • 参数:用于分隔字符串的分隔符,数字(可选,用于指定数组的大小)
    • 作用:基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中,分隔符可以是字符串,也可以是RegExp对象
    var color = 'red,blue,yellow,black';
    var color1 = color.split(',');        // =>['red','blue','yellow','black']
    var color2 = color.split(',',2);    // =>['red','blue']
    var color3 = color.split(/[^\,]+/); // =>["", ",", ",", ",", ""] 
    

字符串比较

  • localeCompare()
    • 这个方法用于比较两个字符串,并返回下列值中的一个
    • 如果字符串在字母表中应该排在字符串参数之前,则返回负数(大多情况下为-1)'a'.localeCompare('c') // -1
    • 如果相等,则返回0 'a'.localeCompare('a') // 0
    • 如果排在字符串参数之前,则返回正数(大多数情况下为1)'c'.localeCompare('a') // 1

字符串操作方法

  • slice(start, end)
    • 创建新的字符串,字符串截取,负值从结尾计数
    • 负值与字符串的长度相加
    • str.slice(1, 3) // el
    • str.slice(2) // llo
    • str.slice(-4, -1) // ell
    • str.slice(-4) // ello
  • substring(start, end)
    • 创建新的字符串,字符串截取,不接受负值
    • 负值转化为0
    • str.substring(1, 3) // el
    • str.substring(2) // llo
    • str.substring(-4) // hello 负值0
  • substr(start, length)
    • 创建新的字符串,字符串截取,负值从结尾计数
    • 第一个位置的负值参数加上字符串长度后转为正数
    • str.substring(1, 3) // ell
    • str.substring(2) // llo 一个值,相当于从开始截到最后
    • str.substring(-2) // lo负值相当于从位数计数
  • concat()参数:一个或多个字符串
    • 所有字符串方法都会返回新字符串。它们不会修改原始字符串
    • str.concat("@",str2);//hello@world
  • repeat(n)(ES6新增) 参数:重复次数
    • 如果传入负数,则报错,传入小数和NaN等同于传入0
    • str.repeat(2) // hellohello

字符方法

  • chartAt() 基于0的字符位置
    • 返回字符串中指定下标(位置)的字符串
    • str.chartAt(1) // e
  • charCodeAt()基于0的字符位置
    • 返回字符串中指定索引的字符 unicode 编码
    • str.charCodeAt(1) // 101

字符串位置方法

  • indexOf() // 要搜索的字符串,开始搜索的位置(可选)
    • 从前开始,搜索到第一个匹配的子字符串后就停止运行
    • 搜索给定的字符串,如果找到则返回位置,否则返回-1
    • str.indexOf("o") // 4
  • lastIndexOf()
    • str.lastIndexOf("o") // 4
    • 从后开始,搜索到第一个匹配的子字符串后就停止运行
    • 搜索给定的字符串,如果找到则返回位置,否则返回-1
  • includes() (ES6新增)
    • 返回布尔值,表示是否找到了参数字符串
    • 使用第2个参数n时,对从第n个位置开始直到字符串结束的字符
    • str.includes("o") // true
    • str.includes("e", 1) // true
    • str.includes("e", 3) // false
  • startsWith() (ES6新增)
    • 返回布尔值,表示参数字符串是否在源字符串的头部
    • 使用第2个参数n时,对从第n个位置开始直到字符串结束的字符
    • str.startsWith("o") // false
    • str.startsWith("h") // true
    • str.startsWith("e", 1) // true
    • str.startsWith("e", 3) // false
  • endsWith() (ES6新增)
    • 返回布尔值,表示参数字符串是否在源字符串的尾部
    • 使用第2个参数n时,对前面n个字符
    • str.endsWith("o") // true
    • str.endsWith("e") // false
    • str.endsWith("e", 1) // false
    • str.endsWith("e", 3) // true

去空格

  • trim() 方法用于去除字符串的左右空格
    • var str3 = ' hello '; str3.trim() // hello

字符串大小写转换

  • toLowerCase()// 转小写 HELLO => hello
  • toLocaleLowerCase()// 针对地区转小写 HELLO => hello
  • toUpperCase()// 转大写 hello => HELLO
  • toLocaleUpperCase()// 针对地区转大写 hello => HELLO

字符串的模式匹配方法

  • match()

    • 参数:一个正则表达式或RegExp对象,返回一个数组
    ar text = "cat, bat, sat, fat";  
    var pattern = /.at/; 
     
    //与 pattern.exec(text)相同 
    var matches = text.match(pattern);         
    alert(matches.index);             //0 
    alert(matches[0]);                 //"cat" 
    alert(pattern.lastIndex);          //0 
    
  • search()

    • 参数:一个正则表达式或RegExp对象
    • 返回字符串中第一个匹配项的索引,如果没有找到,则返回-1
    var text = "cat, bat, sat, fat";  
    var pos = text.search(/at/); 
    alert(pos);   //1 
    
  • replace()

    • 参数:一个RegExp对象或者一个字符串(这个字符串不会被转换成正则表达式),一个字符串或一个函数
    • 如果传入的是字符串,则只会替换第一个子字符串,
    • 要想替换所有的子字符串,则需要传入一个正则表达式,而且要指定全局(g)标志
    var text = 'cat , bat , sat , fat';
    var result = text.replace('at','ond');
    console.log(result); // =>'cont , bat , sat , fat'
    
    result = text.replace(/at/g,'ond');
    console.log(result); //=>'cont , bont , sont , font'
    
    • 当第二个参数为函数时函数的返回值作为替换字符串。与第二个参数是字符串一样,如果第一个参数是正则表达式,并且全局匹配,则这个函数的方法将被多次调用,每次匹配都会被调用。
    • 该函数的参数
      • match:匹配的子串
      • p1,p2...:假如replace()方法的第一个参数是RegExp对象,则代表第n个括号匹配的字符串。
      • offset:匹配到的子字符串在原字符串中的偏移量。(比如,如果原字符串是“abcd”,匹配到的子字符串时“bc”,那么这个参数是1)
      • 被匹配的原字符串
    function replacer(match , p1 , p2 , p3 , offset , string){
        // p1 is nondigits, p2 digits, and p3 non-alphanumerics
        console.log(`${match}
                     ${p1}
                     ${p2}
                     ${p3}
                     ${offset}
                     ${string}`); 
        /* => abc12345#$*%
             abc
             12345
             #$*%
             0
             abc12345#$*%"    */         
        console.log([p1, p2, p3].join(' - ')); // => "abc - 12345 - #$*%"
        return [p1, p2, p3].join(' - ');
    }
    var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); // =>"abc - 12345 - #$*%"