mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-28 21:00:56 +08:00
feat(curriculum): Add interactive examples to How Can You Replace Parts of a String with Another (#63229)
This commit is contained in:
parent
f3631ac648
commit
3b0c6c5172
@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-can-you-replace-parts-of-a-string-with-another
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
In JavaScript, there are many scenarios where you may need to replace a portion of a string with another string.
|
||||
|
||||
@ -23,35 +23,47 @@ string.replace(searchValue, newValue);
|
||||
|
||||
The `newValue` is the value that will replace the `searchValue`. Here's a simple example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let text = "I love JavaScript!";
|
||||
console.log(text); // "I love JavaScript!"
|
||||
let newText = text.replace("JavaScript", "coding");
|
||||
|
||||
console.log(newText); // Output: "I love coding!"
|
||||
console.log(newText); // "I love coding!"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, the word `JavaScript` is found within the string and is replaced with `coding`.
|
||||
|
||||
The `replace()` method is case-sensitive, meaning that it will only find exact matches of the `searchValue`. For example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let sentence = "I enjoy working with JavaScript.";
|
||||
console.log(sentence); // "I enjoy working with JavaScript."
|
||||
let updatedSentence = sentence.replace("javascript", "coding");
|
||||
|
||||
console.log(updatedSentence); // Output: "I enjoy working with JavaScript."
|
||||
console.log(updatedSentence); // "I enjoy working with JavaScript."
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, since `javascript` (with lowercase `j`) does not match `JavaScript` (with uppercase `J`), the replacement is not made.
|
||||
|
||||
By default, the `replace()` method will only replace the first occurrence of the `searchValue`. If the value appears multiple times in the string, only the first one will be replaced:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let phrase = "Hello, world! Welcome to the world of coding.";
|
||||
console.log(phrase); // "Hello, world! Welcome to the world of coding."
|
||||
let updatedPhrase = phrase.replace("world", "universe");
|
||||
|
||||
console.log(updatedPhrase); // Output: "Hello, universe! Welcome to the world of coding."
|
||||
console.log(updatedPhrase); // "Hello, universe! Welcome to the world of coding."
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Notice that only the first occurrence of `world` is replaced with `universe`.
|
||||
|
||||
The `replace()` method in JavaScript is a powerful and flexible tool for string manipulation.
|
||||
|
||||
Loading…
Reference in New Issue
Block a user