Javascript replaceAll is not a function Error
|

Javascript replaceAll is not a function Error: 2 Fixes

ES2021 now includes the String.prototype.replaceAll() method. However, if you are getting a TypeError: replaceAll is not a function error, it means that either your browser or the current Node.js (<15.0) version does not yet support this method. Check the browser compatibility below.

replaceAll browser compatibility (MDN)

Fix 1: Create a polyfill with replace() method

You can create a polyfill for String.prototype.replaceAll() and use the String.prototype.replace() method with a regular expression that has the global (“g“) flag set.

const p = 'apples are round, and apples are juicy.';
console.log(p.replace('apples', 'oranges'));
// expected output: "oranges are round, and apples are juicy."


const regex = /apples/g;
console.log(p.replace(regex, 'oranges'));
// expected output: "oranges are round, and oranges are juicy."
/**
 * String.prototype.replaceAll() polyfill
 * https://gomakethings.com/how-to-replace-a-section-of-a-string-with-another-one-with-vanilla-js/
 * @author Chris Ferdinandi
 * @license MIT
 */
if (!String.prototype.replaceAll) {
	String.prototype.replaceAll = function(str, newStr){

		// If a regex pattern
		if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
			return this.replace(str, newStr);
		}

		// If a string
		return this.replace(new RegExp(str, 'g'), newStr);

	};
}

Fix 2: Use Babel to transpile

Use Babel! “Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments”

You can configure the babel configuration file .babelrc and use “corejs” to be “3.16” or above

{
    "presets": [
        [
            "@babel/preset-env", 
            {
                "corejs": "3.16"
            }
        ]
    ]
}

Related articles:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *