mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-03-26 08:01:08 -04:00
feat(curriculum): Add interactive examples to How Can You Extract a Substring from a String lesson (#63202)
This commit is contained in:
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-can-you-extract-a-substring-from-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
When working with strings in JavaScript, you often need to extract a portion or substring from a larger string.
|
||||
|
||||
@@ -25,46 +25,62 @@ string.slice(startIndex, endIndex);
|
||||
|
||||
Let's look at a simple example of extracting part of a string:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let message = "Hello, world!";
|
||||
let greeting = message.slice(0, 5);
|
||||
|
||||
console.log(greeting); // Output: Hello
|
||||
console.log(greeting); // Hello
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, `slice(0, 5)` extracts characters starting from index `0` up to but not including index `5`. As a result, the word `Hello` is extracted.
|
||||
|
||||
If you omit the second parameter, `slice()` will extract everything from the start index to the end of the string:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let message = "Hello, world!";
|
||||
let world = message.slice(7);
|
||||
|
||||
console.log(world); // Output: world!
|
||||
console.log(world); // world!
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, `slice(7)` extracts the string from index `7` to the end of the string, resulting in `world!`.
|
||||
|
||||
You can also use negative numbers as indexes. When you use a negative number, it counts backward from the end of the string:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let message = "JavaScript is fun!";
|
||||
let lastWord = message.slice(-4);
|
||||
|
||||
console.log(lastWord); // Output: fun!
|
||||
console.log(lastWord); // fun!
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this case, `slice(-4)` extracts the last four characters from the string, giving us `fun!`.
|
||||
|
||||
Let's say you want to extract a section from the middle of a string. You can provide both the starting and ending indexes to precisely control which part of the string you want:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let message = "I love JavaScript!";
|
||||
let language = message.slice(7, 17);
|
||||
|
||||
console.log(language); // Output: JavaScript
|
||||
console.log(language); // JavaScript
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, `slice(7, 17)` extracts the substring starting at index 7 and ending right before index `17`, which is the word `JavaScript`.
|
||||
|
||||
The `slice()` method is a powerful tool for extracting parts of a string in JavaScript.
|
||||
|
||||
Reference in New Issue
Block a user