前端理论总结(js)——字符串操作方法

1、charAt(index): 返回指定索引处的字符串

const str = "Hello, world!";
const char = str.charAt(6); // "w"

2、charCodeAt(index): 返回指定索引处的字符的 Unicode 的值

const str = "Hello";
const code = str.charCodeAt(0); // 72, 'H' 的 Unicode 编码

3、concat(str1, str2, ...): 连接多个字符串,返回连接后的字符串的副本

const str1 = "Hello";
const str2 = " ";
const str3 = "World!";
const result = str1.concat(str2, str3); // "Hello World!"


4、fromCharCode(): 将 Unicode 值转换成实际的字符串

const char = String.fromCharCode(72, 101, 108, 108, 111); // "Hello"

5、indexOf(str): 返回 str 在父串中第一次出现的位置,若没有则返回-1

const str = "Hello, world!";
const index = str.indexOf("world"); // 7
const notFound = str.indexOf("Java"); // -1

6、lastIndexOf(str): 返回 str 在父串中最后一次出现的位置,若没有则返回-1

const str = "Hello, world! Hello again!";
const lastIndex = str.lastIndexOf("Hello"); // 14


7、match(regex): 搜索字符串,并返回正则表达式的所有匹配

const str = "The rain in Spain stays mainly in the plain.";
const matches = str.match(/\bin\b/g); // ["in", "in", "in"]

8、replace(str1, str2):str1 也可以为正则表达式,用 str2 替换 str1

        将指定的字符串或正则表达式匹配的部分替换成另一个字符串:

const str = "Hello, world!";
const newStr = str.replace("world", "JavaScript"); // "Hello, JavaScript!"

   str1 也可以是正则表达式:

const str = "Hello, world!";
const newStr = str.replace(/world/i, "JavaScript"); // "Hello, JavaScript!"

9、search(regex): 基于正则表达式搜索字符串,并返回第一个匹配的位置

const str = "The quick brown fox jumps over the lazy dog";
const position = str.search("fox"); // 16


10、slice(start, end):返回字符索引在 start 和 end(不含)之间的子串

const str = "Hello, world!";
const subStr = str.slice(0, 5); // "Hello"

11、split(sep,limit):将字符串分割为字符数组,limit 为从头开始执行分割的最大数量

const str = "apple,banana,cherry";
const fruits = str.split(",", 2); // ["apple", "banana"]

12、substr(start,length):从字符索引 start 的位置开始,返回长度为 length 的子串

const str = "Hello, world!";
const subStr = str.substr(7, 5); // "world"


13、substring(from, to):返回字符索引在 from 和 to(不含)之间的子串

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

14、toLowerCase():将字符串转换为小写

const str = "Hello, World!";
const lowerStr = str.toLowerCase(); // "hello, world!"

15、toUpperCase():将字符串转换为大写

const str = "Hello, World!";
const upperStr = str.toUpperCase(); // "HELLO, WORLD!"

16、valueOf():返回原始字符串值

const str = "Hello, world!";
const value = str.valueOf(); // "Hello, world!"

ヾ( ̄▽ ̄)Bye~Bye~

ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值