How to perform a str_replace in JavaScript, replacing text in JavaScript?

Estimated read time 2 min read

In JavaScript, you can use the replace() method to perform a str_replace operation and replace text in a string. Here’s an example:

const str = 'Hello, World!';

// Replace 'Hello' with 'Hi'
const newStr = str.replace('Hello', 'Hi');

console.log(newStr); // "Hi, World!"

In the above example, we use the replace() method on the str variable to replace the word “Hello” with “Hi”. The replace() method returns a new string with the specified text replaced.

You can also use a regular expression with the replace() method to perform more complex replacements. For example, to replace all occurrences of a word, you can use a regular expression with the global flag (/g). Here’s an example:

const str = 'The quick brown fox jumps over the lazy dog';

// Replace all occurrences of 'the' (case-insensitive) with 'a'
const newStr = str.replace(/the/ig, 'a');

console.log(newStr); // "a quick brown fox jumps over a lazy dog"

In the above example, we use a regular expression (/the/ig) with the replace() method to replace all occurrences of the word “the” (case-insensitive) with the letter “a”. The g flag indicates that the replacement should be performed globally (i.e., for all occurrences of the pattern), and the i flag indicates that the search should be case-insensitive.

Note that the replace() method does not modify the original string; it returns a new string with the specified text replaced. If you want to modify the original string, you need to assign the result of the replace() method back to the original variable.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply