目录

ES6 - 新的字符串方法( New String Methods)

以下是方法列表及其描述。

Sr.No 方法和描述
1 String.prototype.startsWith(searchString,position = 0)

如果接收者以searchString开头,则返回true; 该位置允许您指定要检查的字符串的起始位置。

2 String.prototype.endsWith(searchString,endPosition = searchString.length)

如果接收者以searchString开头,则返回true; 该位置允许您指定要检查的字符串的起始位置。

3 String.prototype.includes(searchString,position = 0)

如果接收者包含searchString,则返回true; position允许您指定要搜索的字符串的开始位置。

4 String.prototype.repeat(count)

返回接收器,连续计数次数。

模板文字

Template literals是允许嵌入表达式的字符串文字。 Templatestrings字符串使用反向标记(``)而不是单引号或双引号。 因此,模板字符串可以写成 -

var greeting = `Hello World!`; 

字符串插值和模板文字

正如所示,模板字符串可以使用占位符来使用$ {}语法进行字符串替换。

Example 1

var name = "Brendan"; 
console.log('Hello, ${name}!');

成功执行上述代码后,将显示以下输出。

Hello, Brendan!

Example 2: Template literals and expressions

var a = 10; 
var b = 10; 
console.log(`The sum of ${a} and ${b} is  ${a+b} `);

成功执行上述代码后,将显示以下输出。

The sum of 10 and 10 is 20 

Example 3: Template literals and function expression

function fn() { return "Hello World"; } 
console.log(`Message: ${fn()} !!`);

成功执行上述代码后,将显示以下输出。

Message: Hello World !!

多行字符串和模板文字

模板字符串可以包含多行。

Example

var multiLine = `
   This is 
   a string 
   with multiple 
   lines`; 
console.log(multiLine)

成功执行上述代码后,将显示以下输出。

This is 
a string 
with multiple 
line

String.raw()

ES6包含原始字符串的标记函数String.raw,其中反斜杠没有特殊含义。 String.raw使我们能够像在正则表达式文字中一样编写反斜杠。 请考虑以下示例。

var text =`Hello \n World` 
console.log(text)  
var raw_text = String.raw`Hello \n World ` 
console.log(raw_text)

成功执行上述代码后,将显示以下输出。

Hello 
World 
Hello \n World

String.fromCodePoint()

静态字符串。 fromCodePoint()方法返回使用指定的unicode代码点序列创建的字符串。 如果传递了无效的代码点,该函数将抛出RangeError。

console.log(String.fromCodePoint(42))        
console.log(String.fromCodePoint(65, 90))

成功执行上述代码后,将显示以下输出。

* 
AZ
<上一篇.ES6 - Strings
ES6 - Arrays.下一篇>
↑回到顶部↑
WIKI教程 @2018