Here are four new uses of strings in JavaScript6:
1. New representation method of Unicode characters
Unicode characters are usually 21 bits, while ordinary JavaScript characters (mostly) are 16 bits and can be encoded into UTF-16. Characters over 16 bits need to be represented by 2 regular characters.
For example, the following code will output a Unicode rocket character ('/uD83D/uDE80'), you can try it in the browser console:
console.log('/uD83D/uDE80');In ECMAScript 6, new representation methods can be used, which are more concise:
console.log('/u{1F680}');2. Multi-line string definition and template string
Template strings provide three useful syntax features.
First, template strings support embedded string variables:
let first = 'Jane'; let last = 'Doe'; console.log(`Hello ${first} ${last}!`); // Hello Jane Doe!Second, template strings support directly defining multi-line strings:
let multiLine = ` This is a string with multiple lines`;
Third, if you prefix the string with String.raw , the string will remain original. The backslash (/) will not mean escaped, and other professional characters, such as /n, will not be escaped:
let raw = String.raw`Not a newline: /n`; console.log(raw === 'Not a newline: //n'); // true
3. Loop through strings
A string can traverse a loop, you can loop each character in the string using for-of :
for (let ch of 'abc') { console.log(ch); } // Output: // a // b // cAlso, you can split the string into a character array using the splitter (...):
let chars = [...'abc']; // ['a', 'b', 'c']
4. String contains judgment and repeated copy strings
There are three new ways to check whether a string contains another string:
> 'hello'.startsWith('hell') true > 'hello'.endsWith('ello') true > 'hello'.includes('ell') trueThese methods have an optional second parameter indicating the starting position of the search:
> 'hello'.startsWith('ello', 1) true > 'hello'.endsWith('hell', 4) true > 'hello'.includes('ell', 1) true > 'hello'.includes('ell', 2) false repeat() method can copy strings repeatedly:
> 'doo '.repeat(3) 'doo doo doo '
Summarize
The above are four new uses of strings in Javascript 6. Have you learned it? I hope this article will be helpful to everyone. If you have any questions, you can leave a message to communicate.