JS字符串常用方法及其示例

49 阅读2分钟
let str='abcnba'

1.concat

连接两个或多个字符串,得到一个新的字符串

const a=str.concat('mba')//abcnbamba

2.charAt

从字符串中找到指定索引的字符

const a=str.charAt(3)//n

3.charCodeAt

得到0到65535之间的整数,表示给定索引处的 UTF-16代码单元

const a=charCodeAt(0)//97
const a=charCodeAt(3)//110

4.includes

判断一个字符串是否包含在另一个字符串中

const a=str.includes('m')//false
const b=str.includes('nb')//true

5.indexOf

返回值第一次出现的索引,没有就返回-1

const a=str.indexOf('b')//1
const b=str.indexOf('m')//-1

6.padEnd

用一个字符串填充当前字符串,返回指定长度的字符串。从末尾开始填充

const a=str.padEnd(8,'m')//abcnbamm
const a=str.padEnd(8,'mm')//abcnbamm
const a=str.padEnd(8,'mba')//abcnbamb

7.padStart

用一个字符串填充当前字符串,返回指定长度的字符串。从首部开始填充

const a=str.padStart(8,'m')//mmabcnba
const a=str.padStart(8,'mm')//mmabcnba
const a=str.padStart(8,'mbz')//mbabcnba

8.repeat

字符串复制指定次数

const a=str.repeat(2)//'abcnbaabcnba' 如果传递包含小数,则会舍弃小数(2.9==>2)

9.match

检索返回一个字符串匹配正则表达式的结果

const a=str.match(/b/)//['b', index: 1, input: 'abcnba', groups: undefined]
const a=str.match(/b/g)//['b','b']

10.replace

替换指定字符

const a=str.replace('a','b')//bbcbna
const a=str.replace(/a/g, "z")//zbcbnz

11.search

** 返回字符串中第一个匹配项的索引; 如果没有找到匹配项, 则返回 -1**

const a= str.search('b')//1
const a= str.search('z')//-1

12.toLowerCase

转小写

let str= 'nBa'
str.toLowerCase()//nba

13.toUpperCase

转大写

str.toUpperCase()//ABCNBA

14.trim

删除字符串两端的空白字符,中间无法去除

const a=' a bc '
a.trim()//'a bc' 

15.substr

从起始索引号提取字符串中指定数目的字符 str.substr(start, 长度)

const a=str.substr(1)//bcnba
const a=str.substr(1,3)//bcn

16.substring

提取字符串中两个指定的索引号之间的字符 str.substring[start, end)

const a=str.substring(1)//bcnba
const a=str.substring(1,3)//bc

17.slice

截取字符串,包含开始,不包含结束 str.slice[start, end)

const a=str.slice(1)//bcnba
const a=str.slice(1,3)//bc

18.split

把字符串分割为子字符串数组

const str='aa,bb'
const a=str.slice()//['aa,bb']
const a=str.slice("")//['a','a',',','b','b']