ES2015字符串的扩展

来源:互联网 发布:linux 删除u盘分区 编辑:程序博客网 时间:2024/05/12 07:08

includes()、startsWith()、endsWith()

传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。 
ES6又提供了三种新方法

includes():返回布尔值,表示是否找到了参数字符串startsWith():返回布尔值,表示参数字符串是否在源字符串的头部endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
var s = "hello world!";s.startsWith("hello"); // trues.endsWith("!"); // trues.includes("o"); //true
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

这3个方法都支持第二个参数,表示开始索索的位置

var s = 'Hello world!';s.startsWith('world', 6) // trues.endsWith('Hello', 5) // trues.includes('Hello', 6) // false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

上面的代码表示,使用第二个参数n时,endWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置知道字符串结束。

repeat()

repeat方法返回一个新字符串,表示把原字符串重复n

'x'.repeat(3)   // "xxx"'hello'.repeat(2)   // "hellohello"'na'.repeat(0)  // ""
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

参数如果是小数,会被取整

'na'.repeat(2.9)    // "nana"
  • 1
  • 1

如果repeat()的参数是负数或者Infinity,会报错

'na'.repeat(Infinity)// RangeError'na'.repeat(-1)// RangeError
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

参数NaN等同于0

'na'.repeat(NaN) // ""
  • 1
  • 1

padStart(),padEnd()

ES7推出了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。

'x'.padStart(5,'ab')    // "ababx"'x'.padStart(4,'ab')    // "abax"'x'.padEnd(5, 'ab') // 'xabab''x'.padEnd(4, 'ab') // 'xaba'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

如果省略第二个参数,则会用空格补全长度

'x'.padStart(4) // '   x''x'.padEnd(4) // 'x   '
  • 1
  • 2
  • 1
  • 2

padStart()常见用途是为数值补全指定位数:

'1'.padStart(10, '0') // "0000000001"'12'.padStart(10, '0') // "0000000012"'123456'.padStart(10, '0') // "0000123456"
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

另一个用途是提升字符串格式:

'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
  • 1
  • 2
  • 1
  • 2

模板字符串

传统的JavaScript语言,输出模板通常是这样写的。

$('#result').append(  'There are <b>' + basket.count + '</b> ' +  'items in your basket, ' +  '<em>' + basket.onSale +  '</em> are on sale!');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

上面这种写法相当繁琐不方便,ES6引入了模板字符串解决这个问题。

$('#result').append(`  There are <b>${basket.count}</b> items   in your basket, <em>${basket.onSale}</em>  are on sale!`);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

// 普通字符串`In JavaScript '\n' is a line-feed.`// 多行字符串`In JavaScript this is not legal.`console.log(`string text line 1string text line 2`);// 字符串中嵌入变量var name = "Bob", time = "today";`Hello ${name}, how are you ${time}?`
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

模板字符串中嵌入变量,需要将变量名写在${}之中。

function authorize(user, action) {  if (!user.hasPrivilege(action)) {    throw new Error(      // 传统写法为      // 'User '      // + user.name      // + ' is not authorized to do '      // + action      // + '.'      `User ${user.name} is not authorized to do ${action}.`);  }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

模板字符串之中还能调用函数。

function fn() {  return "Hello World";}`foo ${fn()} bar`// foo Hello World bar
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

如果模板字符串中的变量没有声明,将报错

// 变量place没有声明var msg = `Hello, ${place}`;// 报错
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

如果需要引用模板字符串本身,在需要时执行,可以像下面这样写。

// 写法一let str = 'return ' + '`Hello ${name}!`';let func = new Function('name', str);func('Jack') // "Hello Jack!"// 写法二let str = '(name) => `Hello ${name}!`';let func = eval.call(null, str);func('Jack') // "Hello Jack!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

标签模板

模板字符串的功能,不仅仅是上面这些。它可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串。这被称为“标签模板”功能(tagged template)。

alert`123`// 等同于alert(123)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

标签模板其实不是模板,而是函数调用的一种特殊形式。“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。

0 0
原创粉丝点击