2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
id: bd7123c9c450eddfaeb5bdef
|
|
|
|
title: Use Bracket Notation to Find the Nth Character in a String
|
|
|
|
challengeType: 1
|
2019-02-14 12:24:02 -05:00
|
|
|
videoUrl: 'https://scrimba.com/c/cWPVJua'
|
2019-07-31 11:32:23 -07:00
|
|
|
forumTopicId: 18343
|
2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --description--
|
|
|
|
|
2018-09-30 23:01:58 +01:00
|
|
|
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.
|
2020-11-27 19:02:05 +01:00
|
|
|
|
|
|
|
Remember that computers start counting at `0`, so the first character is actually the zeroth character.
|
2020-03-25 08:07:13 -07:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
```js
|
|
|
|
var firstName = "Ada";
|
|
|
|
var secondLetterOfFirstName = firstName[1]; // secondLetterOfFirstName is "d"
|
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --instructions--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
**Hint:** Try looking at the example above if you get stuck.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --hints--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
The `thirdLetterOfLastName` variable should have the value of `v`.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
2020-11-27 19:02:05 +01:00
|
|
|
assert(thirdLetterOfLastName === 'v');
|
|
|
|
```
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
You should use bracket notation.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
2018-09-30 23:01:58 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --seed--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
## --after-user-code--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
2018-10-20 21:02:47 +03:00
|
|
|
(function(v){return v;})(thirdLetterOfLastName);
|
2018-09-30 23:01:58 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
## --seed-contents--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
// Setup
|
|
|
|
var lastName = "Lovelace";
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
// Only change code below this line
|
|
|
|
var thirdLetterOfLastName = lastName; // Change this line
|
|
|
|
```
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --solutions--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
var lastName = "Lovelace";
|
|
|
|
var thirdLetterOfLastName = lastName[2];
|
|
|
|
```
|