JavaScript String.Replace() not working
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 :
function formatString(str) {
for (var k in formatChart) {
str = str.split(k).join(formatChart[k]);
}
return str;
}
You are searching the string for the resultant values, not the keys. Try this instead:
var formatString = function(str)
{
for (var k in formatChart)
{
while (str.indexOf(k) != -1)
str = str.replace(k, formatChart[k]);
}
return str;
};
string.indexOf(formatChart[k]) != -1
is wrong. When iterating over an Object (which you actually shouldn't do) the k
value is the Key. You want string.indexOf(k) != -1
.
Instead of this:
while (string.indexOf(formatChart[k]) != -1)
Try this:
while (string.indexOf(k) != -1)
There is an small mistake in your function. replace
while (string.indexOf(formatChart[k]) != -1)
by
while (string.indexOf(k) != -1)
and see the results
Here's a slightly different regex version. This escapes the regex chars in the things to replace so we can use the global replace of the regex replace function. You need double backslashes in front of the brackets so that you're left with on backslash when passed as a regex.
var formatChart = {
'\\[newline\\]' : '<br />',
'\\[tab\\]' : ' ',
'\\[space\\]' : ' '
};
var str = "Hello[newline]World[tab]Tab[space]Hello[newline]Done";
function formatString(str) {
for (var i in formatChart) {
str = str.replace(new RegExp(i, "gi"), formatChart[i]);
}
return(str);
}
You can see it in action here: http://jsfiddle.net/jfriend00/pj2Kr/
Here's a fiddle using regex: http://jsfiddle.net/msTuC/
Incorrect: while (string.indexOf(formatChart[k]) != -1)
Correct: while (string.indexOf(k) != -1)
精彩评论