前端Vue日常工作中--字符串方法

56 阅读2分钟

前端Vue日常工作中--字符串方法

当处理JavaScript中的字符串时,以下是一些常见的JavaScript字符串方法的介绍:

  1. charAt(index) - 获取指定位置的字符

    • 返回给定索引位置的字符。
    const str = "Hello";
    console.log(str.charAt(0)); // Output: "H"
    
  2. charCodeAt(index) - 获取指定位置字符的Unicode值

    • 返回给定索引位置字符的Unicode值。
    const str = "Hello";
    console.log(str.charCodeAt(0)); // Output: 72
    
  3. concat(string1, string2, ...) - 连接字符串

    • 连接两个或多个字符串,并返回一个新字符串。
    const str1 = "Hello";
    const str2 = " ";
    const str3 = "World";
    console.log(str1.concat(str2, str3)); // Output: "Hello World"
    
  4. indexOf(substring, start) - 查找子字符串的位置

    • 返回子字符串第一次出现的位置,如果没有找到则返回-1。
    const str = "Hello World";
    console.log(str.indexOf("World")); // Output: 6
    
  5. lastIndexOf(substring, start) - 反向查找子字符串的位置

    • 返回子字符串最后一次出现的位置,如果没有找到则返回-1。
    const str = "Hello World, World!";
    console.log(str.lastIndexOf("World")); // Output: 13
    
  6. slice(start, end) - 提取子字符串

    • 返回从开始到结束索引的子字符串。
    const str = "Hello World";
    console.log(str.slice(0, 5)); // Output: "Hello"
    
  7. substring(start, end) - 提取子字符串

    • 返回从开始到结束索引的子字符串,与slice类似。
    const str = "Hello World";
    console.log(str.substring(0, 5)); // Output: "Hello"
    
  8. substr(start, length) - 提取子字符串

    • 返回从指定位置开始的指定长度的子字符串。
    const str = "Hello World";
    console.log(str.substr(0, 5)); // Output: "Hello"
    
  9. toUpperCase() - 转换为大写

    • 返回字符串的大写形式。
    const str = "Hello";
    console.log(str.toUpperCase()); // Output: "HELLO"
    
  10. toLowerCase() - 转换为小写

    • 返回字符串的小写形式。
    const str = "Hello";
    console.log(str.toLowerCase()); // Output: "hello"
    
  11. length - 返回字符串的长度

    const str = "Hello, World!";
    console.log(str.length); // 输出:13
    
  12. replace(oldValue, newValue) - 替换字符串中的子字符串

    const str = "Hello, World!";
    console.log(str.replace("World", "Universe")); // 输出:Hello, Universe!
    
  13. split(separator) - 将字符串分割成数组

    const str = "Hello, World!";
    console.log(str.split(", ")); // 输出:["Hello", "World!"]
    
  14. trim() - 移除字符串两端的空白字符

trim() 方法是 JavaScript 字符串对象的一个内建方法,用于移除字符串两端的空白字符,包括空格、制表符、换行符等。它不会改变原始字符串,而是返回一个新的字符串。

const str = "   Hello, World!   ";
const newstr = str.trim();
console.log(newstr); // 输出: "Hello, World!"