Heim  >  Artikel  >  Web-Frontend  >  Wissenswerte neue String-Methoden in ES6

Wissenswerte neue String-Methoden in ES6

青灯夜游
青灯夜游nach vorne
2021-07-22 18:36:562247Durchsuche

Dieser Artikel stellt Ihnen die neuen Methoden in ES6-Strings vor. Das Verständnis dieser Methoden wird Ihnen hilfreich sein.

Wissenswerte neue String-Methoden in ES6

1. String.fromCodePoint()

Zunächst müssen wir String.fromCharCode() erwähnen. Aber String.fromCodePoint() ist eine Verbesserung gegenüber String.fromCharCode().

Methodenname js-Version Unterschied
formCharCode es5 kann Codepunkte größer als 0xFFFF nicht erkennen, und es kommt zu einem Überlauf. fromCodePoint ist das Gegenteil
formCodePoint es6 Wenn mehrere Parameter übergeben werden, werden sie zu einer Zeichenfolge kombiniert und zurückgegeben, fromCharCode jedoch nicht

Wissenswerte neue String-Methoden in ES6

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!"

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

String.raw`Hi\\n`;      \\ "Hi\\\\n"
String.raw`Hi\\n` == "Hi\\\\n";           \\ true

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

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;
}

3. 实例方法:codePointAt()

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

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

  • 实例方法

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

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

只通过A.方法 就能调用

function A(){}
A.sayHello = function(){
	console.log("Hello")
}
A.sayHello();     //Hello
  • 原型方法

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

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

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

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

3.2 JavaScript字符存储格式

Wissenswerte neue String-Methoden in ES6

Wissenswerte neue String-Methoden in ES6

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

s.codePointAt(0).toString(16)      // "20bb7"

3.3 用途

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

Wissenswerte neue String-Methoden in ES6

4. 实例方法:normalize()

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

Wissenswerte neue String-Methoden in ES6

&#39;\u01D1&#39;===&#39;\u004F\u030C&#39; //false
&#39;\u01D1&#39;.length // 1
&#39;\u004F\u030C&#39;.length // 2

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

4.1 不接收参数

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

&#39;\u01D1&#39;.normalize() === &#39;\u004F\u030C&#39;.normalize()     // true

4.2 接收参数

&#39;\u004F\u030C&#39;.normalize(&#39;NFC&#39;).length // 1
&#39;\u004F\u030C&#39;.normalize(&#39;NFD&#39;).length // 2

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

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

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

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

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

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

let s = &#39;Hello world!&#39;;
s.startsWith(&#39;world&#39;, 6) // true
s.endsWith(&#39;Hello&#39;, 5) // true
s.includes(&#39;Hello&#39;, 6) // false

6. 实例方法:repeat()

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

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

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

7.1 作用

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

两个参数:

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

7.2  传两个参数

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

7.3 省略第二个参数

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

&#39;x&#39;.padStart(4) 	// &#39;   x&#39;
&#39;x&#39;.padEnd(4) 		// &#39;x   &#39;

7.4 用途

  • 为数值补全指定位数
&#39;1&#39;.padStart(10,&#39;0&#39;)       // "0000000001"
&#39;123456&#39;.padStart(10, &#39;0&#39;) // "0000123456"
  • 提示字符串格式
&#39;12&#39;.padStart(10,&#39;YYYY-MM-DD&#39;)   // "YYYY-MM-12"
&#39;09-12&#39;.padStart(10, &#39;YYYY-MM-DD&#39;) // "YYYY-09-12"

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

  • trimStart() 去掉字符串头部空格
  • trimEnd()  去掉字符串末尾的空格
const s = &#39;  abc  &#39;;

s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"

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

9. 实例方法:replaceAll()

9.1 replace()

只能替换第一个匹配

&#39;aabbcc&#39;.replace(&#39;b&#39;,&#39;_&#39;)    // aa_bcc

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

&#39;aabbcc&#39;.replace(/b/g, &#39;_&#39;)    // &#39;aa__cc&#39;

9.2 replaceAll()

  • 第一个参数传字符串
&#39;aabbcc&#39;.replaceAll(&#39;b&#39;, &#39;_&#39;)         // "aa__cc"
  • 第一个参数传正则表达式   如果没有/g修饰符  replaceAll会报错
// 不报错
&#39;aabbcc&#39;.replace(/b/, &#39;_&#39;)

// 报错
&#39;aabbcc&#39;.replaceAll(/b/, &#39;_&#39;)
  • 第二个参数是一个字符串,表示替换的文本,其中可以使用一些特殊字符串。
// $& 表示匹配的字符串,即`b`本身
// 所以返回结果与原字符串一致
&#39;abbc&#39;.replaceAll(&#39;b&#39;, &#39;$&&#39;)
// &#39;abbc&#39;

// $` 表示匹配结果之前的字符串
// 对于第一个`b`,$` 指代`a`
// 对于第二个`b`,$` 指代`ab`
&#39;abbc&#39;.replaceAll(&#39;b&#39;, &#39;$`&#39;)
// &#39;aaabc&#39;

// $&#39; 表示匹配结果之后的字符串
// 对于第一个`b`,$&#39; 指代`bc`
// 对于第二个`b`,$&#39; 指代`c`
&#39;abbc&#39;.replaceAll(&#39;b&#39;, `$&#39;`)
// &#39;abccc&#39;

// $1 表示正则表达式的第一个组匹配,指代`ab`
// $2 表示正则表达式的第二个组匹配,指代`bc`
&#39;abbc&#39;.replaceAll(/(ab)(bc)/g, &#39;$2$1&#39;)
// &#39;bcab&#39;

// $$ 指代 $
&#39;abc&#39;.replaceAll(&#39;b&#39;, &#39;$$&#39;)
// &#39;a$c&#39;
  • 第二个参数除了可以是字符串外也可以是一个函数
&#39;aabbcc&#39;.replaceAll(&#39;b&#39;, () => &#39;_&#39;)   // &#39;aa__cc&#39;

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

Das obige ist der detaillierte Inhalt vonWissenswerte neue String-Methoden in ES6. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:掘金--csdn来挖墙脚. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen