📜  字符串长度 javascript (1)

📅  最后修改于: 2023-12-03 15:09:22.303000             🧑  作者: Mango

字符串长度 javascript

在 JavaScript 中,字符串长度是指字符串中包含字符的总数。我们可以使用字符串的 length 属性来获取字符串的长度。

下面是一个示例:

const str = 'hello world';
const length = str.length;
console.log(length); // 输出 11

在上面的示例中,我们定义一个字符串变量 str,使用字符串的 length 属性来获取字符串的长度,并将其赋值给 length 变量。最后,我们将 length 变量的值打印到控制台。

除了字符串的 length 属性外,您还可以使用 String.prototype 上的其他一些方法来查询和操作字符串的长度。下面是一些示例:

  1. charAt(index)

    返回字符串中指定索引位置的字符。

    const str = 'hello world';
    const char = str.charAt(1);
    console.log(char); // 输出 e
    
  2. charCodeAt(index)

    返回字符串中指定索引位置的字符的 Unicode 编码。

    const str = 'hello world';
    const code = str.charCodeAt(1);
    console.log(code); // 输出 101
    
  3. substring(startIndex, endIndex)

    返回字符串中指定位置的子字符串。startIndex 参数是子字符串的第一个字符的索引,endIndex 参数是子字符串中最后一个字符后面的索引。如果省略 endIndex 参数,则子字符串将一直延伸到字符串的末尾。

    const str = 'hello world';
    const substring = str.substring(3, 7);
    console.log(substring); // 输出 lo w
    
  4. slice(startIndex, endIndex)

    substring 方法相同,除了 slice 方法允许负数索引。如果 startIndex 是负数,则它被解释为从字符串末尾开始的索引。如果 endIndex 是负数,则它被解释为从字符串末尾开始的索引,回退的数量等于它的绝对值。

    const str = 'hello world';
    const slice1 = str.slice(3, 7);
    console.log(slice1); // 输出 lo w
    
    const slice2 = str.slice(-5, -1);
    console.log(slice2); // 输出 worl
    
  5. indexOf(searchValue, fromIndex)

    返回字符串中第一次出现指定值的索引。如果没有找到该值,则返回 -1。fromIndex 参数指定在哪里开始搜索。如果省略 fromIndex 参数,则从字符串开头开始搜索。

    const str = 'hello world';
    const index1 = str.indexOf('world');
    console.log(index1); // 输出 6
    
    const index2 = str.indexOf('l', 4);
    console.log(index2); // 输出 9
    
  6. lastIndexOf(searchValue, fromIndex)

    indexOf 方法相同,但搜索是从字符串的末尾开始的。

    const str = 'hello world';
    const index = str.lastIndexOf('l');
    console.log(index); // 输出 9
    

字符串长度是 JavaScript 中一项基本的概念,了解字符串的长度和如何操作字符串可以帮助您更好地处理字符串数据。