字符串的子串识别
- includes()方法,如果在字符串中检测到指定文本则返回true,否则返回false。
- startsWith()方法,如果在字符串的其实部分检测到指定文本则返回true,否则返回false。
- endsWhit() 方法, 如果在字符串的结束部分检测到指定文本则返回true,否则返回false。
以上三个方法传入的第一个参数都接受两个参数:第一个参数指定要搜索的文本;第二个参数是可选的,指定一个开始的搜索位置。如果指定了第二个参数,则includes方法和startsWith方法会从这个缩影值开始匹配,endsWith这个方法则从这个索引值减去欲搜索文本的长度位置开始正向匹配,示例如下:
let msg = "hello world!";
//判断
console.log(msg.includes('hello'));
//判断结束
console.log(msg.endsWith('!'));
//判断开始
console.log(msg.startsWith('h'));
console.log(msg.startsWith('0'));
console.log(msg.endsWith('world!'));
console.log(msg.includes('x'));
console.log(msg.startsWith('o',4));
console.log(msg.endsWith('o',8));
console.log(msg.includes('0',8));
输出结果
➜ ES6练习 git:(master) ✗ node string.js
true
true
true
false
true
false
true
true
false
repeat() 方法
es6为字符串提供了一个repeat方法,接受一个number类型的参数,表示该字符串的重复次数,返回值是当前字符串重复一定的次数,示例如下:
console.log('x'.repeat(2));
console.log('hello'.repeat(3));
输出结果
xx
hellohellohello
模板字面量
基础语法
模板字面量最简单的用法,看起来好像只是用反披号“`”替换了单、双引号,举个例子:
let message = `Hello world!`;
console.log(message);
console.log(typeof message);
console.log(message.length);
输出结果
Hello world!
string
12
如果你想在字符串中使用“`”符号,那么用反斜杠“\”转义就可以,示例代码如下:
let message = `\`hello\` word!` ;
console.log(message);
console.log(typeof message);
console.log(message.length);
输出结果
`hello` word!
string
13
而在模板字符串中不需要转义单、双引号。
多行字符串
es5的做法,先看示例:
var message = "Muletiline \
string";
console.log(message);
输出结果
Muletiline string
当把字符串message打印控制台时其并未按照夸行为方式显示,因为反斜杠在此处代表行的延续,而非真正代表新的一行。
如果想输出新的一行,需要手动加入换行符:
var message = "Muletiline\n
string";
console.log(message);
输出结果
Muletiline
string
es6简化多行字符串,其极大地简化了多行字符串的创建过程。如果你需要在字符串中添加新的一行,只需要在代码中直接换行,此处的黄浩将同步出现在结果中。示例如下:
let message = `Hello
String!`;
console.log(message);
输出结果
Hello
String!
字符串占位符
占位符由一个左侧的${和右侧的}符号组成,中间可以包含任意的JavaScript表达式。示例如下:
示例1
let name = "nicholas",
message = `Hello,${name}`;
console.log(message);
输出结果
Hello,nicholas
示例2
let count = 10,
price = 0.25,
message = `${count} items cost $${(count * price).toFixed(2)}.`;
console.log(message);
输出结果
10 items cost $2.50.
示例3
let name = "Nicholas",
message = `Hello, ${
`my name is ${name}`
}`;
console.log(message);
输出结果
Hello, my name is Nicholas
网友评论