search
HomeWeb Front-endJS TutorialNew string methods worth knowing about in ES6

This article will introduce you to the new methods in ES6 strings. Understanding these methods will be helpful to you.

New string methods worth knowing about in ES6

1. String.fromCodePoint()

First of all, we must mention String.fromCharCode(), both methods are used Convert unicode code to corresponding text. But String.fromCodePoint() is an improvement over String.fromCharCode().

Method name js version Difference
formCharCode es5 cannot recognize code points greater than 0xFFFF, and overflow will occur. fromCodePoint is the opposite
formCodePoint es6 When multiple parameters are passed in, they will be combined into a string and returned, but fromCharCode will not meeting

New string methods worth knowing about 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字符存储格式

New string methods worth knowing about in ES6

New string methods worth knowing about in ES6

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

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

3.3 用途

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

New string methods worth knowing about in ES6

4. 实例方法:normalize()

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

New string methods worth knowing about 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;

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

The above is the detailed content of New string methods worth knowing about in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金--csdn来挖墙脚. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.