ES6 新的String对象方法
ES6 新的String对象方法
1.String.prototype.startsWith(searchString, position = 0)
如果文本以searchString开头,则返回true,否则返回false;position用于指定要检查的字符串的开始位置。
2.String.prototype.endsWith(searchString, endPosition = searchString.length)
如果文本以searchString结尾,则返回true,否则返回false;endPosition用于指定要检查的字符串的结束位置。
3.String.prototype.includes(searchString, position = 0)
如果文本包含searchstring,则返回true,否则返回false;position指定要搜索的字符串的开始位置。
4.String.prototype.repeat(count)
该方法返回一个重复包含初始字符串的新字符串,重复次数等于count.
字符串插值和模板文本
模板字符串可以使用占位符来使用${ }语法进行字符串替换,如下所示:
例子1
var name = "Brendan"; console.log('Hello, ${name}!');
输出:
Hello, Brendan!
例子2: 模板文字和表达式
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
例子3: 模板文字与函数表达式
function fn() { return "Hello World"; } console.log(`Message: ${fn()} !!`);
输出
Message: Hello World !!
多行字符串和模板文本
模板字符串可以包含多个行
例子
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()
静态方法String.fromCodePoint()返回使用指定的unicode代码点序列创建的字符串.如果传递了无效的代码点,则函数将引发RangeError。
console.log(String.fromCodePoint(42)) console.log(String.fromCodePoint(65, 90))
如果传递了无效的代码点,则函数将引发RangeError。
输出
* AZ