mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
feat(curriculum): Add interactive examples to How Can You Test if a String Contains a Substring lesson (#63200)
This commit is contained in:
+14
-2
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-can-you-test-if-a-string-contains-a-substring
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
When working with strings in JavaScript, there are many cases where you might need to check whether a string contains a specific substring, which is a smaller part of that string.
|
||||
|
||||
@@ -21,6 +21,8 @@ string.includes(searchValue);
|
||||
|
||||
For the syntax, the `searchValue` is the substring you want to look for within the string. And here's an example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let phrase = "JavaScript is awesome!";
|
||||
let result = phrase.includes("awesome");
|
||||
@@ -28,23 +30,31 @@ let result = phrase.includes("awesome");
|
||||
console.log(result); // true
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, the word `awesome` is found within the string `JavaScript is awesome!`, so the `includes()` method returns `true`.
|
||||
|
||||
It's important to note that the `includes()` method is case-sensitive. This means that the exact match of the characters is required, including their case.
|
||||
|
||||
For example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let phrase = "JavaScript is awesome!";
|
||||
let result = phrase.includes("Awesome");
|
||||
|
||||
console.log(result); // Output: false
|
||||
console.log(result); // false
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Since `Awesome` (with an uppercase `A`) does not match `awesome` (with a lowercase `a`), the result is `false`.
|
||||
|
||||
You can also use the `includes()` method to check for a substring starting at a specific index in the string by providing a second parameter:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let text = "Hello, JavaScript world!";
|
||||
let result = text.includes("JavaScript", 7);
|
||||
@@ -52,6 +62,8 @@ let result = text.includes("JavaScript", 7);
|
||||
console.log(result); // true
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, the search for the substring `JavaScript` starts from the 7th position in the string, ensuring it skips any characters before this position.
|
||||
|
||||
The `includes()` method only returns a `true` or `false` result. It does not provide information on where the substring is located in the string or how many times it occurs. If you need that level of detail, other methods, such as the `indexOf()` method might be more suitable.
|
||||
|
||||
Reference in New Issue
Block a user