Saturday, January 11, 2025
HomeProgrammingjavascript - regex string replace

javascript – regex string replace

In JavaScript, the replace() method allows replacing parts of a string using regular expressions (regex). It takes two arguments: the regex pattern and the replacement string or function.

Example:

javascript
let str = "Hello World";
let result = str.replace(/World/, "JavaScript");
console.log(result); // "Hello JavaScript"

To replace all occurrences, use the global flag g:

javascript
let str = "The sun and the moon";
let result = str.replace(/the/g, "a");
console.log(result); // "The sun and a moon"

The replace() method is ideal for pattern-based string modifications and transformations.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Who is Dolly Parton?

DBMS Examples

2001 in Roman Numerals

Recent Comments

0
Would love your thoughts, please comment.x
()
x