Today we are here to talk about another very useful built-in method that we can use in our daily tasks, the replace javascript method. This method is used to replace all, or part of, a pattern with another string. Let’s analyze its syntax first and then try to dive into its usage. 

The syntax

replace() method syntax
replace() method syntax


  • newString: a new string with some or all matches of a pattern replaced by a new string we specify(notice how the original string is not modified)
  • regexp: a RegExp object or literal that will be replaced by our newSubstring. Treated as verbatim and not interpreted as a regular expression. 
  • substring: a string to be replaced with our newSubString. Only the first occurrence will be replaced
  • newSubstring: the string that will be our replacement for the expression specified earlier(regexp or substring). Some special replacement patterns are also supported in this case; see this link.
  • function: we can also, instead of using newSubstring, specify a function as the second parameter of replace. When this happens, the function will be invoked after the match has been performed. The function’s returning value will be used as the replacement string.

Use case

replace method use case
replace method use case

Also notice as mentioned above, that in case you provide a string as a replacement pattern only its first occurrence will be modified

replace method use case
replace method use case

Other useful resources

For some other cool Javascript resources, you can always look up at our special section here on the blog dedicated to the language. Some useful links:


Replacing part of a string is a common task we all face, and the replace javascript method is an easy and convenient tool to use. Hope this article gave you the means to perform such operation in a more understandable way. Don’t forget to share and follow the blog!


Please enter your comment!
Please enter your name here