Signup/Sign In

How to replace character inside a string in JavaScript?

Answer: Using replace() method

The JavaScript replace() method enables us to replace a substring inside a string with a new substring.

The replace() method first searches for a string for the specified value and then returns a new string where the specified values are replaced. This method replaces only the first occurrence of the word or the character. To replace all the occurrences of the value, we have to use the global (g) modifier.

This method does not change the string but returns a new string with a substring replaced by a new string.

Syntax

string.replace(searchValue, newValue)

Example: Using replace() method

In the given example, we have used the replace() method to replace the string ST with Studytonight.

<!DOCTYPE html>
<html>
<head>
  <title> replace character inside a string</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <script type="text/javascript">
    let myStr = 'Hello, Welcome to ST';
    console.log(myStr);
    let newStr = myStr.replace('ST','Studytonight');
    
    console.log(newStr);
  </script>
</body>
</html>

Output

As we can see in the output that there the string ST is now replaced with the new string Studytonight.

replace() method

Using regular expressions

As we know replace method replaces only the first occurrence of the string, to make this method replace all the occurrences of the string we have to enable the global flag within the regular expressions.

We just have to pass the regular expression at the place of searchValue within the replace() method along with the newValue.

Syntax

str.replace(regexp, newValue);

Example: Using regular expression

In the given example we have used the global flag (g) within the replace() method to replace all the occurrences of JavaScript with JS within the string.

<!DOCTYPE html>
<html>
<head>
  <title> replace character inside a string</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <script type="text/javascript">
    let myStr = 'JavaScript is a Scripting Language and I love JavaScript';
    console.log(myStr);
    
    let newStr = myStr.replace(/JavaScript/g,'JS');
    console.log(newStr);
  </script>
</body>
</html>

Output

replace()

Conclusion

In this lesson, we have discussed how to replace a character inside a string. JavaScript offers replace() method that allows us to replace the character or word with a new character or word within the given string. This method does not change the string it just returns a new string with a substring changed with a new string.



About the author: