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));
上面的代碼應該用它們的HTML替換替換所有出現的「特殊」字符([newline]等)。但它不起作用。JavaScript String.Replace()不起作用
爲什麼?
除了下面,你也將需要從'this.formatChart [K]擺脫''this.'。 'this'指向你的formatString函數 – bcoughlan