js字符串常用方法

js字符串常用方法

1. charAt(index)

可返回指定位置的字符。

console.log("hello world".charAt(0)) // h

2. charCodeAt(index)

可返回指定位置的字符的 Unicode 编码。

console.log("hello world".charCodeAt(0)) // 75

3. concat(str1,str2…)

连接两个或更多字符串,并返回新的字符串。

let str = "hello"
let str1 = " world"
console.log(str.concat(str1)) // hello world

4. endsWith(searchVal,length)

判断当前字符串是否是以指定的子字符串结尾的(区分大小写)。length设置字符串的长度。默认值为原始字符串长度 string.length。

console.log("hello world".endsWith("world")) // true

5. fromCharCode(n1,n2…)

将 Unicode 编码转为字符。

console.log(String.fromChartCode(72,69,76,76,79)) // HELLO

6. indexOf(searchVal*,*start)

返回某个指定的字符串值在字符串中首次出现的位置。

let str="Hello world, welcome to the universe.";
console.log(str.indexOf("e",5)) // 14

7. includes(str)

查找字符串中是否包含指定的子字符串。

console.log("hello world".includes("world")) // true

8. lastIndexOf(searchVal,start)

从后向前搜索字符串,并从起始位置(0)开始计算返回字符串最后出现的位置。

console.log("hello world".lastIndexOf("world")) // 6

9. match(regExp)

查找找到一个或多个正则表达式的匹配。

let str ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let regexp = /[A-E]/gi;
let matches_array = str.match(regexp);
console.log(matches_array); // ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

10. repeat(number)

复制字符串指定次数,并将它们连接在一起返回。

console.log('hello'.repeat(2)) // hellohello

11. replace(searchVal,newVal)

在字符串中查找匹配的子串,并替换与正则表达式匹配的子串。

console.log('hello'.replace('hello','hi')) // hi

12. replaceAll()

在字符串中查找匹配的子串,并替换与正则表达式匹配的所有子串。

console.log('hello hello'.replaceAll('hello','hi')) // hi hi

13. search(searchVal)

用于检索字符串中指定的子字符串或检索与正则表达式相匹配的子字符串的位置。

console.log('hello world'.search('world')) // 6

14. slice(start,end)

提取字符串的片断,并在新的字符串中返回被提取的部分。

console.log('hello world'.slice(1,5)) // ello

15. split(separator,limit)

把字符串分割为字符串数组。limit:该参数可指定返回的数组的最大长度。

let str = 'how are you doing today'
console.log(str.split(' ')) // [how,are,you,dogin,today]

16. startsWith()

查看字符串是否以指定的子字符串开头。

console.log('hello world'.startsWith('hello')) //true

17. substr(start,length)

从起始索引号提取字符串中指定数目的字符。

console.log('hello world'.substr(2,3)) // llo

18. substring(start,end)

提取字符串中两个指定的索引号之间的字符。

console.log('hello world'.substring(2,5)) // llo

19. toLowerCase()

把字符串转换为小写。

console.log('Hello World'.toLowerCase()) // hello world

20. toUpperCase()

把字符串转换为大写。

console.log('Hello World'.toUpperCase()) // HELLO WORLD

21. toLocalLowerCase()

根据本地主机的语言环境把字符串转换为小写。

console.log('Hello'.toLocalLowerCase()) // hello

22. toLocalUpperCase()

根据本地主机的语言环境把字符串转换为大写。

console.log('Hello'.toLocalUpperCase()) // HELLO

23. valueOf()

返回某个字符串对象的原始值。

console.log('hello world'.valueOf()) // hello world

24. toString()

返回一个字符串

console.log('hello'.toString()) // hello
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值