Maison> interface Web> js tutoriel> le corps du texte

ES6中值得了解的新增字符串方法

青灯夜游
Libérer: 2021-07-22 18:40:13
avant
2222 Les gens l'ont consulté

本篇文章给大家介绍一下ES6字符串中的新增方法,了解这些方法对大家有所帮助。

ES6中值得了解的新增字符串方法

1. String.fromCodePoint()

首先要提一下 String.fromCharCode() ,两个方法用途都是将unicode码转为对应的文字。但是String.fromCodePoint()是对String.fromCharCode()的改进。

方法名 js版本 区别
formCharCode es5 不能识别大于0xFFFF的码点,会发生溢出。fromCodePoint与之相反
formCodePoint es6 当传入多个参数时,他们会被合成一个字符串返回,fromCharCode则不会

6.png

2. String.raw()

两种用法:

  • 一种是用于模板字符串,这种用法不应该使用()
  • 另一种是使用(callSite, ...substitutions),两个参数:callSite是模板字符串的调用对象,应该是具有raw属性的对象 { raw: ['foo', 'bar', 'baz'] }

2.1 String.raw ``

将转义字符前加一个斜杠

String.raw`Hi\n${2+3}` \\ "Hi\\5" String.raw`Hi\u000A!` \\ "Hi\\u000A!"
Copier après la connexion

如果原字符串的斜杠已经被转义 即( \n )

String.raw`Hi\\n`; \\ "Hi\\\\n" String.raw`Hi\\n` == "Hi\\\\n"; \\ true
Copier après la connexion

2.2 String.raw(callSite, ...substitutions)

正常来说,这种方法很少使用,但是为了模拟t${0}e${1}s${2}t

String.raw({raw:'test'},3,4,5) // "t3e4s5t" String.raw({raw:['aa','bb','cc'],1+2,3}) // "aa3bb3cc" // 下面这个函数和 `aa${2 + 3}bb${'Java' + 'Script'}cc` 是相等的. String.raw({raw:['aa','bb','cc']},2+3,'java'+'Script') // aa5bbjavaScriptcc
Copier après la connexion

2.3 String.raw()的代码实现

String.raw = function (strings, ...values) { let output = ''; let index; for (index = 0; index < values.length; index++) { output += strings.raw[index] + values[index]; } output += strings.raw[index] return output; }
Copier après la connexion

3. 实例方法:codePointAt()

3.1 实例方法、静态方法、原型方法

首先要说一下什么是实例方法,有可能是我还是个菜鸡,所以刚一听到实例方法不知道它是什么。 js的方法类型有:实例方法、静态方法、原型方法三种。

  • 实例方法

实例方法要用到function这个对象中的prototype属性来定义。实例化对象后才可以使用

function A (){} A.prototype.sayHello = function(){ console.log("Hello") } var a = new A(); a.sayHello(); // Hello
Copier après la connexion
  • 静态方法

只通过A.方法 就能调用

function A(){} A.sayHello = function(){ console.log("Hello") } A.sayHello(); //Hello
Copier après la connexion
  • 原型方法

原型中的方法实例和构造函数都可以访问到

function A(){} A.prototype.sayHello = function(){ console.log("原型方法") } A.sayHello = function(){ console.log("静态方法") } A.sayHello() // "静态方法" A.prototype.sayHello() // "原型方法" let a = new A(); a.sayHello(); // "原型方法"
Copier après la connexion

函数是一个对象,函数对象中的属性 prototype可以想成一个指针,指向一个方法(这样不用每一次用构造函数创造一个新实例后都要将方法重新创建一遍)。这样就好理解了,var a是A的一个引用,也就是指针,a就可以指向sayHello这个方法,如果直接A.sayHello()是会报错的,因为A不是一个指针,a.sayHello()也会报错,因为a不是一个方法对象。

言归正传 codePointAt()的出现是为了解决Unicode码点大于0xFFFF的字符无法读取整个字符的问题

3.2 JavaScript字符存储格式

4.png

5.png

将十进制码点转为十六进制

s.codePointAt(0).toString(16) // "20bb7"
Copier après la connexion

3.3 用途

codePointAt()方法是测试一个字符由两个字节还是由四个字节组成的最简单方法

7.png

4. 实例方法:normalize()

许多欧洲语言有语调符号和重音符号 Unicode提供了两种方法:

8.png

'\u01D1'==='\u004F\u030C' //false '\u01D1'.length // 1 '\u004F\u030C'.length // 2
Copier après la connexion

上面代码 javaScript不能识别他们是一样的

4.1 不接收参数

但是 normalize()方法会将Unicode正视化

'\u01D1'.normalize() === '\u004F\u030C'.normalize() // true
Copier après la connexion

4.2 接收参数

'\u004F\u030C'.normalize('NFC').length // 1 '\u004F\u030C'.normalize('NFD').length // 2
Copier après la connexion

上面代码表示,NFC参数返回字符的合成形式,NFD参数返回字符的分解形式。

不过,normalize方法目前不能识别三个或三个以上字符的合成。这种情况下,还是只能使用正则表达式,通过 Unicode 编号区间判断。

5. 实例方法:includes(), startsWith(), endsWith()

作用:用来确定一个字符串是否包含在另一个字符串中

  • JavaScript有indexOf方法
let a ="abcd"; a.indexOf("b"); // 1 a.indexOf("e"); // -1
Copier après la connexion
  • includes() 返回布尔值 是否包含某字符
a.includes("b"); // true a.includes("f"); // false
Copier après la connexion
  • startsWith(). 返回布尔值,表示参数字符串是否在原字符串的头部
let a = "abc"; a.startsWith("a"); // true a.startsWith("b"); // false
Copier après la connexion
  • endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部
a.endsWith("c"); // true a.endsWith("a"); // false
Copier après la connexion

startsWith()、endsWith()、includes() 都有第二个参数,表示搜索的起始位置。

let s = 'Hello world!'; s.startsWith('world', 6) // true s.endsWith('Hello', 5) // true s.includes('Hello', 6) // false
Copier après la connexion

6. 实例方法:repeat()

作用:返回一个新字符串,表示将原字符串重复多次

  • 正常重复
"x".repeat(3); // "xxx" "hello".repeat(2); // "hellohello"
Copier après la connexion
  • 0
"x".repeat(0) // ""
Copier après la connexion
  • 小数 会被取整 向下取整
"x".repeat(2.5). // "xx"
Copier après la connexion
  • 负数 或 Infinity 报错
"x".repeat(-1) // RangeError "x".repeat(Infinity) // RangeError
Copier après la connexion
  • 在0和-1之间的负数。都被取整成0
"x".repeat(-0.3) // ""
Copier après la connexion
  • NaN 等同于0
"x".repeat(NaN) // ""
Copier après la connexion
  • 字符串 先转为数字
"x".repeat("2") // "xx"
Copier après la connexion

7. 实例方法:padStart(),padEnd()

7.1 作用

用于补全字符串,padStart()用于补全头部。padEnd()用于尾部补全。

两个参数:

  • 第一个:字符串补全生效的最大长度
  • 第二个:用来补全的字符串

7.2 传两个参数

  • 正常补全
'xxx'.padStart(5,"abc"); // "abxxx" 'xxx'.padEnd(5,"abc"); // "xxxab"
Copier après la connexion
  • 原字符串长度 > 或 = 最大长度(即第一个参数),则不生效,返回原字符串
'xxx'.padStart(2,'ab') // "xxx" 'xxx'.padEnd(2,'ab') // "xxx"
Copier après la connexion
  • 用来补全的字符串长度 > 最大长度 补全字符串会被截取
'abc'.padStart(10, '0123456789') // "0123456abc"
Copier après la connexion

7.3 省略第二个参数

省略第二个参数,默认使用空格补全

'x'.padStart(4) // ' x' 'x'.padEnd(4) // 'x '
Copier après la connexion

7.4 用途

  • 为数值补全指定位数
'1'.padStart(10,'0') // "0000000001" '123456'.padStart(10, '0') // "0000123456"
Copier après la connexion
  • 提示字符串格式
'12'.padStart(10,'YYYY-MM-DD') // "YYYY-MM-12" '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
Copier après la connexion

8. 实例方法:trimStart(),trimEnd()

  • trimStart() 去掉字符串头部空格
  • trimEnd() 去掉字符串末尾的空格
const s = ' abc '; s.trim() // "abc" s.trimStart() // "abc " s.trimEnd() // " abc"
Copier après la connexion

浏览器还部署了额外的两个方法,trimLeft()是trimStart()的别名,trimRight()是trimEnd()的别名。这两个用法与trimStart()和trimEnd()相同。

9. 实例方法:replaceAll()

9.1 replace()

只能替换第一个匹配

'aabbcc'.replace('b','_') // aa_bcc
Copier après la connexion

要想替换所有 b ,需要使用 /g 修饰符

'aabbcc'.replace(/b/g, '_') // 'aa__cc'
Copier après la connexion

9.2 replaceAll()

  • 第一个参数传字符串
'aabbcc'.replaceAll('b', '_') // "aa__cc"
Copier après la connexion
  • 第一个参数传正则表达式 如果没有/g修饰符 replaceAll会报错
// 不报错 'aabbcc'.replace(/b/, '_') // 报错 'aabbcc'.replaceAll(/b/, '_')
Copier après la connexion
  • 第二个参数是一个字符串,表示替换的文本,其中可以使用一些特殊字符串。
// $& 表示匹配的字符串,即`b`本身 // 所以返回结果与原字符串一致 'abbc'.replaceAll('b', '$&') // 'abbc' // $` 表示匹配结果之前的字符串 // 对于第一个`b`,$` 指代`a` // 对于第二个`b`,$` 指代`ab` 'abbc'.replaceAll('b', '$`') // 'aaabc' // $' 表示匹配结果之后的字符串 // 对于第一个`b`,$' 指代`bc` // 对于第二个`b`,$' 指代`c` 'abbc'.replaceAll('b', `$'`) // 'abccc' // $1 表示正则表达式的第一个组匹配,指代`ab` // $2 表示正则表达式的第二个组匹配,指代`bc` 'abbc'.replaceAll(/(ab)(bc)/g, '$2$1') // 'bcab' // $$ 指代 $ 'abc'.replaceAll('b', '$$') // 'a$c'
Copier après la connexion
  • 第二个参数除了可以是字符串外也可以是一个函数
'aabbcc'.replaceAll('b', () => '_') // 'aa__cc'
Copier après la connexion

更多编程相关知识,请访问:编程视频!!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:掘金--csdn来挖墙脚
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!