JavaScript String replace() method

The replace() method in JavaScript is used to search a string for a specified pattern, and replace the pattern with a specified replacement string. This method takes two arguments: the pattern to search for, and the replacement string. If the pattern is found, the replace() method returns a new string with the pattern replaced by the replacement string. If the pattern is not found, the replace() method returns the original string.

Here is an example of how the replace() method works:

const string1 = 'Hello, world!';

const result = string1.replace('world', 'moon');

// the result will be: 'Hello, moon!'

In the code example above, we first declare a string called string1 that contains the text Hello, world!. We then use the replace() method to search the string1 string for the pattern world, and replace it with the string moon. The replace() method takes two arguments: the pattern to search for, and the replacement string. In this case, we pass in the string world as the first argument, and the string moon as the second argument to the replace() method.

As a result of calling the replace() method, the result variable will be set to 'Hello, moon!', which is the string1 string with the pattern world replaced by the replacement string moon. If the replace() method was called with a pattern that was not found in the string1 string, the result variable would be set to the original string1 string.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: