字符串常用内置方法

  • `length`: 返回字符串的长度。
  const str = "Hello";
  console.log(str.length);  // 输出: 5
  • `charAt(index)`: 返回指定索引位置的字符。
  const str = "Hello";
  console.log(str.charAt(0));  // 输出: "H"
  console.log(str.charAt(3));  // 输出: "l"
  • `substring(startIndex, endIndex)`: 返回位于指定索引范围内的子字符串。
  const str = "Hello, World!";
  console.log(str.substring(0, 5));  // 输出: "Hello"
  console.log(str.substring(7));     // 输出: "World!"
  • `toUpperCase()`: 将字符串转换为大写。
  const str = "hello";
  console.log(str.toUpperCase());  // 输出: "HELLO"
  • `toLowerCase()`: 将字符串转换为小写。
  const str = "WORLD";
  console.log(str.toLowerCase());  // 输出: "world"
  •  `trim()`: 移除字符串两端的空格。
  const str = "  Hello, World!  ";
  console.log(str.trim());  // 输出: "Hello, World!"
  •  `indexOf()` 查找指定子字符串在字符串中首次出现的位置索引。如果未找到子字符串,则返回 -1。
string.indexOf(searchValue, startIndex)
// searchValue:要搜索的子字符串。
// startIndex:可选参数,指定搜索的起始位置的索引。省略该参数时,默认从字符串的开头开始搜索。

const str = "Hello, World!";
const index1 = str.indexOf("World");
console.log(index1);  // 输出: 7

const index2 = str.indexOf("o", 5);
console.log(index2);  // 输出: 8
  • `split(separator, limit)`: 将字符串分割为子字符串数组。
// separator默认','

const str = "1-2-3-4-5";
const array1 = str.split("-");
const array2 = str.split("-", 3);
console.log(array1);  // 输出: ["1", "2", "3", "4", "5"]
console.log(array2);  // 输出: ["1", "2", "3"]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值