Tuesday, 1 December 2009

JavaScript - ReplaceAll Function

Approach1:
JavaScript ReplaceAll Function:
String.prototype.ReplaceAll = function(stringToFind, stringToReplace) {


if (stringToFind == null stringToFind == '') return this;


var result = "";
var temp = this;


var index = temp.indexOf(stringToFind);


if (index == -1) return this;


do {
var targetLength = index + stringToReplace.length;
temp = temp.replace(stringToFind, stringToReplace);
result += temp.substring(0, targetLength);
temp = temp.substring(targetLength, temp.length);
index = temp.indexOf(stringToFind);
} while (index != -1);


// to add any remaining data
result += temp;


return result;


}

How to use it:

function Test() {


var data = "Hi, my name is Pooya Khamooshi; I am expert in everything (potentially)!";
var replaceMe = 'Pooya';
var replaceWith = "<b>" + replaceMe + "<\b>";


if (data.indexOf(str) == -1)
document.writeln("no match found");
else
document.write(data.ReplaceAll(replaceMe, replaceWith));
}

Approach2:
Use regular expression

This approach is easier and shorter but it requires that you know exactly what your regular expression is.

var str = "My name is Pooya Khamooshi and I have understood that there are many things I am not expert in";
var pattern = /\s/g;
str.replace(pattern, ''); // this removes all the spaces from the text above.

No comments: