var formatChart = {
'[newline]' : '<br />',
'[tab]' : ' ',
'[space]' : ' '
};
// Formats a string according to the formatting chart
var formatString = function(string)
{
for (var k in formatChart)
{
while (string.indexOf(formatChart[k]) != -1)
string = string.replace(k, this.formatChart[k]);
}
return string;
};
var str = "Hello[newline]World[tab]Tab[space]Hello[newline]Done";
alert(formatString(str));
The code above is supposed to replace all occurrences of “special” characters ([newline], etc) with their HTML equivalents. But it’s not working.
Why?
Be carefull, replace in javascript works with regex. This is not what you are trying to do. An usual way to do is use combined join and split functions.
Plus, you are testing if the replaced string exists in a first place (formatChart[k]) but you want to test if the replacee (k) is in that string.
here is a sample code :