mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-03-25 23:02:05 -04:00
feat(curriculum): Add interactive examples to How Can You Find the Position of a Substring in a String (#63194)
This commit is contained in:
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-can-you-find-the-position-of-a-substring-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
When working with strings in JavaScript, there may be times when you need to locate the position of a specific substring within a larger string.
|
||||
|
||||
@@ -22,25 +22,35 @@ In this context, an **argument** is a value you give to a function or method whe
|
||||
|
||||
Here is an example of using the `indexOf()` method to find the position for the string `awesome`:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let sentence = "JavaScript is awesome!";
|
||||
let position = sentence.indexOf("awesome!");
|
||||
console.log(position); // 14
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, the word `awesome` starts at index `14` in the string `JavaScript is awesome!`, so the `indexOf()` method returns `14`.
|
||||
|
||||
Now, let's see what happens when the substring isn't found:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let sentence = "JavaScript is awesome!";
|
||||
let position = sentence.indexOf("fantastic");
|
||||
console.log(position); // -1
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Since the word `fantastic` does not appear in the string, the method returns `-1`.
|
||||
|
||||
You can also specify where to begin searching within the string by providing a second argument to `indexOf()`. Here’s an example:
|
||||
You can also specify where to begin searching within the string by providing a second argument to `indexOf()`. Here's an example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let sentence = "JavaScript is awesome, and JavaScript is powerful!";
|
||||
@@ -48,16 +58,22 @@ let position = sentence.indexOf("JavaScript", 10);
|
||||
console.log(position); // 27
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this case, the search for `JavaScript` begins after the 10th character, and so the second occurrence of `JavaScript` is found at index `27`.
|
||||
|
||||
It is important to note that the `indexOf()` method is case sensitive.
|
||||
|
||||
In this example, the following would return `-1` because the capital letter `F` is not found in the string `freeCodeCamp`.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
console.log("freeCodeCamp".indexOf("F")) // -1
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Using `indexOf()` can be very useful when you need to check if a substring is present in a string and to determine its position for further operations.
|
||||
|
||||
# --questions--
|
||||
|
||||
Reference in New Issue
Block a user