learning to use JavaScript’s replaceAll() method
JavaScript’s replaceAll() method is totally different from JS regex’s replace() method. I encounter my aha moment in working with strings and wanting to replace the current string of something with a new string of something else, which is when I discovered String.prototype.replaceAll() in MDN Web Docs.
According to MDN Web Docs: The replaceAll()
method returns a new string with all matches of a pattern
replaced by a replacement
. The pattern
can be a string or a RegExp
, and the replacement
can be a string or a function to be called for each match. The original string is left unchanged
SYNTAX structure in replaceAll()
- replaceAll(regexp, newSubstr)
- replaceAll(regexp, replacerFunction)
- replaceAll(substr, newSubstr)
- replaceAll(substr, replacerFunction)
Furthermore, I implement replaceAll() method on this Leetcode problem.
var defangIPaddr = function(address) {//solution with replaceAll()
return address.replaceAll('.', "[.]");//solution using regex in replace()
return address.replace(/[.]/g,"[.]");
//or try this (below)
return address.replace(/\./g,"[.]");
//solution using two methods in split() and join()
return address.split('.').join('[.]')
}
Please clap if you enjoy this read. Thank you.
Happy coding.
References
• “String.prototype.replaceAll()”. MDN Web Docs.