js字符串基本方法总结

1、字符方法:

charAt()、at()、charCodeAt()、codePointAt()

参数:基于0的字符位置

at()、charAt()返回给定位置上的字符,其中at()针对码点大于0xFFFF的字符是es6提供的方法;codePointAt()、charCodeAt()返回给定位置上的字符编码,其中codePointAt() 针对4字节UTF-16编码的字符串是es6提供的方法。

//判断一个字符由4个还是2个字节组成

function is32Bit(char){

return c.codePointAt(0) > 0xFFFF;

}

fromCharCode()、fromCodePoint()

参数:一个或多个字符编码

fromCharCode()、fromCodePoint()将一个或多个字符编码转换成字符串,是定义在String对象上的方法,其中fromCodePoint()可以转换码点大于0xFFFF的字符是es6提供的 方法。

String.fromCharCode(104,101,108,108,111);

String.fromCodePoint(0x20BB7);

2、字符串位置方法

indexOf()、lastIndexOf()、includes()、startsWith()、endsWith()

参数:搜索字符串,搜索位置(可选)

indexOf()、lastIndexOf()返回搜索字符串的位置,否则返回为-1,includes()、startsWith()、endsWith()返回布尔值是es6提供的方法,其中endsWith()第二参数表示在前n个字 符中进行搜索。

let str = ‘Hello String’;

str.indexOf('o');//4

str.includes('o');//true

3、去空格

trim()

参数:无

trim()用于去除字符串左右的空格。

‘  Hello  ’.trim();//Hello

4、字符串大小写转换

toLowerCase()、toLocaleLowerCase()、toUpperCase()toLocaleUpperCase()

参数:无

toLowerCase()、toLocaleLowerCase()、toUpperCase()toLocaleUpperCase()对字符串进行大小写转换。

5、字符串拼接

concat()

参数:一个或多个字符串

concat()将一个或多个字符串进行拼接,更多对是使用‘+’进行拼接。

‘Hell’.concat('o',' ','String');//Hello String

6、字符串剪切方法

substring()、slice()

参数:开始位置,结束位置

substring()、slice()返回子字符串。

'Hello String'.slice(0,2);//"He"

'Hello String'.substring(0,2);//"He"

substr()

参数:开始位置,字符串个数

'Hello String'.substr(0,2);//"He"

repeat()

参数:字符串重复次数

‘ha’.repeat(2);//haha

7、模式匹配方法

match()

参数:一个正则表达式或RegExp对象

match()返回一个数组。在字符串上调用这个方法本质上与调用RegExp的exec()方法相同。

'Hello'.match(/He/);

search()

参数:一个正则表达式或RegExp对象

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

'Hello'.search(/at/);//-1

replace()

参数:一个RegExp对象或者一个字符串(这个字符串不会被转换成正则表达式),一个字符串或一个函数

replace()进行替换的时候,如果传入的是字符串,则只会替换第一个子字符串,要想替换所有的子字符串,则需要传入一个正则表达式,而且要指定全局(g)标志。

'Hello'.replace(/He/,'HA');//HAllo

8、字符串分隔

split()

参数:分隔符可以是数字、字符、正则等

split()返回一个分隔后的数组。

'Hello String'.plit(' ');//["Hello","String"]

猜你喜欢

转载自blog.csdn.net/hh921227/article/details/78227311