js截取字符串 记录日常开发中的小搜索

在 JavaScript 中,可以使用 substring()substr() 方法来截取字符串。

substring(startIndex [, endIndex]) 方法用于从字符串中提取子字符串。

  • startIndex 参数是必需的,表示要截取的子字符串的起始位置。
  • endIndex 参数是可选的,表示要截取的子字符串的结束位置。如果省略,则将截取到字符串尾部。

substring() 方法返回一个新的字符串,不会修改原始字符串。

例如,假设有一个字符串 "Hello, world!" ,要从第 7 个字符开始截取,可以使用以下代码:

const str = "Hello, world!";
    const subStr = str.substring(7);
    console.log(subStr); // 输出 "world!"

如果要从第 1 个字符开始截取到第 5 个字符,则可以使用以下代码:

const str = "Hello, world!";
    const subStr = str.substring(0, 5);
    console.log(subStr); // 输出 "Hello"

substr(startIndex [, length]) 方法用于从字符串中提取子字符串。

  • startIndex 参数是必需的,表示要截取的子字符串的起始位置。
  • length 参数是可选的,表示要截取的子字符串的长度。如果省略,则将截取到字符串尾部。

substr() 方法返回一个新的字符串,不会修改原始字符串。

  • 例如,假设有一个字符串 "Hello, world!" ,要从第 7 个字符开始截取,可以使用以下代码:
const str = "Hello, world!";
    const subStr = str.substr(7);
    console.log(subStr); // 输出 "world!"

如果要从第 1 个字符开始截取 5 个字符,则可以使用以下代码:

const str = "Hello, world!";
    const subStr = str.substr(0, 5);
    console.log(subStr); // 输出 "Hello"

原文链接:https://juejin.cn/post/7227012644508483642 作者:早起的年轻人

(0)
上一篇 2023年4月29日 上午10:23
下一篇 2023年4月29日 上午10:33

相关推荐

发表回复

登录后才能评论