2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7db7367417b2b2512b9e
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 匹配字符串的末尾
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-08-04 15:14:01 +08:00
|
|
|
forumTopicId: 301352
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
|
|
|
在上一个挑战中,学习了使用`^`符号来搜寻字符串开头的匹配模式。还有一种方法可以搜寻字符串末尾的匹配模式。
|
|
|
|
|
|
|
|
可以使用正则表达式的`美元`符号`$`来搜寻字符串的结尾。
|
2020-08-04 15:14:01 +08:00
|
|
|
|
|
|
|
```js
|
|
|
|
let theEnding = "This is a never ending story";
|
|
|
|
let storyRegex = /story$/;
|
|
|
|
storyRegex.test(theEnding);
|
|
|
|
// Returns true
|
|
|
|
let noEnding = "Sometimes a story will have to end";
|
|
|
|
storyRegex.test(noEnding);
|
|
|
|
// Returns false
|
|
|
|
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
使用`$`在字符串`caboose`的末尾匹配`"caboose"`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你应该在正则表达式使用美元符号`$`来搜寻`'caboose'`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(lastRegex.source == 'caboose$');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你的正则表达式不应该使用任何标志。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(lastRegex.flags == '');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
你应该在字符串`'The last car on a train is the caboose'`的末尾匹配`'caboose'`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(lastRegex.test('The last car on a train is the caboose'));
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-04 15:14:01 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|