js中字符串常见的方法

在JavaScript中,字符串是一种原始数据类型,同时也是一个对象。因此,字符串对象具有一些内置的方法,可以用于处理和操作字符串数据。以下是一些常见的JavaScript字符串方法,并为每个方法提供一个简单的使用案例:

length 属性 - 获取字符串长度

const text = "Hello, World!";
const length = text.length;
console.log(length); // Output: 13

索引访问和切片

const text = "Hello, World!";
console.log(text[0]);     // Output: 'H'
console.log(text.slice(7, 12)); // Output: 'World'

indexOf() 和 lastIndexOf() 方法 - 查找子字符串的索引

const text = "Hello, World!";
console.log(text.indexOf("World")); // Output: 7
console.log(text.lastIndexOf("o")); // Output: 7 (last occurrence of 'o')

startsWith() 和 endsWith() 方法 - 检查字符串开头和结尾

const text = "Hello, World!";
console.log(text.startsWith("Hello")); // Output: true
console.log(text.endsWith("World!"));  // Output: false

toLowerCase() 和 toUpperCase() 方法 - 转换大小写

const text = "Hello, World!";
console.log(text.toLowerCase()); // Output: "hello, world!"
console.log(text.toUpperCase()); // Output: "HELLO, WORLD!"

trim() 方法 - 去除开头和结尾的空白字符

const text = "  Hello, World!  ";
console.log(text.trim()); // Output: "Hello, World!"

replace() 方法 - 替换子字符串

const text = "Hello, World!";
const newText = text.replace("Hello", "Hi");
console.log(newText); // Output: "Hi, World!"

split() 方法 - 拆分字符串为数组

const text = "apple,banana,orange";
const fruitsArray = text.split(",");
console.log(fruitsArray); // Output: ['apple', 'banana', 'orange']

charAt() 方法 - 获取指定索引处的字符

const text = "Hello, World!";
console.log(text.charAt(0)); // Output: 'H'
console.log(text.charAt(7)); // Output: 'W'

includes() 方法 - 检查字符串是否包含指定子字符串

const text = "Hello, World!";
console.log(text.includes("World")); // Output: true
console.log(text.includes("hello")); // Output: false (case-sensitive)

charCodeAt() 方法 - 获取指定索引处字符的Unicode值

const text = "Hello, World!";
console.log(text.charCodeAt(0)); // Output: 72
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值