前端JS 字符串方法 String

目录

1. length

2. toUpperCase()

3. toLowerCase()

4. trim()

5. charAt()

6. indexOf()

7. lastIndexOf()

8. slice()

9. substring()

10. replace()

11. split()

12. includes()

13. startsWith()

14. endsWith()

15. repeat()


1. length

获取字符串的长度。

var str = "Hello, World!"; console.log(str.length); // 输出 13

2. toUpperCase()

将字符串中的所有字母转换为大写。

var str = "hello"; console.log(str.toUpperCase()); // 输出 "HELLO"

3. toLowerCase()

 将字符串中的所有字母转换为小写。:

var str = "HELLO"; console.log(str.toLowerCase()); // 输出 "hello"

4. trim()

移除字符串两端的空白字符(空格、换行、制表符等)

var str = " Hello World! "; console.log(str.trim()); // 输出 "Hello World!"

5. charAt()

返回指定位置的字符。

var str = "Hello"; console.log(str.charAt(1));

6. indexOf()

查找指定子字符串在字符串中首次出现的位置,如果未找到返回 -1。

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

7. lastIndexOf()

查找指定子字符串在字符串中最后一次出现的位置。

var str = "Hello, Hello, World!"; console.log(str.lastIndexOf("Hello")); // 输出 7

8. slice()

提取字符串的一部分,返回一个新的字符串,原字符串不变。

var str = "Hello, World!"; console.log(str.slice(0, 5)); // 输出 "Hello"

9. substring()

 提取字符串的一部分,与 slice() 类似,但不能接受负数参数。

var str = "Hello, World!"; console.log(str.substring(0, 5)); // 输出 "Hello"

10. replace()

替换字符串中的某个子字符串或正则表达式匹配的内容

var str = "Hello, World!"; 
console.log(str.replace("World", "JavaScript"));
 // 输出 "Hello, JavaScript!"

11. split()

将字符串分割为数组,依据指定的分隔符。

var str = "apple,banana,cherry"; 
console.log(str.split(","));
 // 输出 ["apple", "banana", "cherry"]

12. includes()

检查字符串是否包含指定的子字符串,返回 truefalse

var str = "Hello, World!";
 console.log(str.includes("World")); 
// 输出 true

13. startsWith()

检查字符串是否以指定的子字符串开头,返回 truefalse

var str = "Hello, World!";
console.log(str.startsWith("Hello")); 
// 输出 true

14. endsWith()

检查字符串是否以指定的子字符串结尾,返回 truefalse

var str = "Hello, World!"; 
console.log(str.endsWith("World!")); 
// 输出 true

15. repeat()

返回一个新的字符串,表示将原字符串重复指定次数。

var str = "Hello"; 
console.log(str.repeat(3)); 
// 输出 "HelloHelloHello"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值