JS 字符串常用方法

21 阅读2分钟
  • charAt() :返回指定索引处的字符。

    let str = "hello";
    let char = str.charAt(1); // char 是 "e"
    
  • charCodeAt() :返回指定索引处字符的 Unicode 编码。

    let str = "hello";
    let code = str.charCodeAt(1); // code 是 101
    
  • concat() :连接两个或多个字符串,返回连接后的新字符串。

    let str1 = "hello";
    let str2 = "world";
    let newStr = str1.concat(" ", str2); // newStr 是 "hello world"
    
  • includes() :判断一个字符串是否包含另一个字符串,返回布尔值。

    let str = "hello world";
    let result = str.includes("world"); // result 是 true
    
  • indexOf() :返回字符串中首次出现指定值的索引,如果未找到则返回 -1。

    let str = "hello world";
    let index = str.indexOf("world"); // index 是 6
    
  • lastIndexOf() :返回字符串中最后一次出现指定值的索引,如果未找到则返回 -1。

    let str = "hello world world";
    let index = str.lastIndexOf("world"); // index 是 12
    
  • slice() :提取字符串的片段,并以新的字符串返回被提取的部分。

    let str = "hello world";
    let newStr = str.slice(0, 5); // newStr 是 "hello"
    
  • substring() :返回字符串的一个子集,不接受负索引。

    let str = "hello world";
    let newStr = str.substring(0, 5); // newStr 是 "hello"
    
  • substr() :从起始索引号提取字符串中指定数目的字符。

    let str = "hello world";
    let newStr = str.substr(0, 5); // newStr 是 "hello"
    
  • toLowerCase() :将整个字符串转换为小写。

    let str = "HELLO WORLD";
    let newStr = str.toLowerCase(); // newStr 是 "hello world"
    
  • toUpperCase() :将整个字符串转换为大写。

    let str = "hello world";
    let newStr = str.toUpperCase(); // newStr 是 "HELLO WORLD"
    
  • trim() :去除字符串两端的空白字符。

    let str = "  hello world  ";
    let newStr = str.trim(); // newStr 是 "hello world"
    
  • split() :通过指定分隔符将字符串分割为数组。

    let str = "hello world";
    let arr = str.split(" "); // arr 是 ["hello", "world"]
    
  • replace() :替换与正则表达式匹配的子串,返回新字符串。

    let str = "hello world";
    let newStr = str.replace("world", "everyone"); // newStr 是 "hello everyone"
    
  • match() :找到一个或多个正则表达式的匹配,返回一个数组。

    let str = "hello world";
    let matches = str.match(/world/); // matches 是 ["world"]
    
  • search() :执行正则表达式匹配搜索,返回第一个匹配项的索引。

    let str = "hello world";
    let index = str.search(/world/); // index 是 6
    
  • startsWith() :判断字符串是否以指定的子字符串开始,返回布尔值。

    let str = "hello world";
    let result = str.startsWith("hello"); // result 是 true
    
  • endsWith() :判断字符串是否以指定的子字符串结束,返回布尔值。

    let str = "hello world";
    let result = str.endsWith("world"); // result 是 true