Replace All function using Javascript

The function replaceAll() replaces all occurrences of substring in string with a replacement value.

Method 1. Standard function.

// Standard function, pass the string, search and replace parameters
function replaceAll(str, search, replace) {
	if (search === "" || str === "") { return str; }
	return str.split(search).join(replace);
}

Example 1 Usage:

result = replaceAll(str, " you " " ya'all ");

Method 2. Prototype function.

// Standard function, pass the string, search and replace parameters
String.prototype.replaceAll = function(search, replace) {
	if (search === "") { return this; }
	return this.split(search).join(replace);
}

Example 2 Usage:

// Prototype function takes a "this" value prepended with dot, and arguments provided for search and replace.
result = str.replaceAll(" you ", " ya'all ");

Given this string:
str = "As an exercise, you really can't do better than climbing. Indoor climbing will improve all aspects of your physical condition. You will see improvement in your balance, flexibility, and agility and develop both upper and lower body strength. Best of all, you will burn calories at a higher rate than most strenuous workouts and will do it before you know it.";

Result for both functions:
result == "As an exercise, ya'all really can't do better than climbing. Indoor climbing will improve all aspects of your physical condition. You will see improvement in your balance, flexibility, and agility and develop both upper and lower body strength. Best of all, ya'all will burn calories at a higher rate than most strenuous workouts and will do it before ya'all know it.";

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use