December 2023
Intermediate to advanced
242 pages
5h 28m
English
The replace() method replaces matches with the given string. The pattern may be a string or a regex:
| | const str = "fish and chips"; |
| | |
| | // Using a string as the argument |
| | console.log(str.replace("and", "&")); // → fish & chips |
| | |
| | // Using a regex as the argument |
| | console.log(str.replace(/and/, "&")); // → fish & chips |
If the global flag is set, the method replaces every match it finds in the string:
| | const str = "$5, $10, $20"; |
| | const re = /\$/g; |
| | |
| | console.log(str.replace(re, "€")); // → €5, €10, €20 |
Read now
Unlock full access