0
var formatChart = {
    '[newline]' : '<br />', 
    '[tab]' : '&nbsp;&nbsp;&nbsp;&nbsp;', 
    '[space]' : '&nbsp;'
}; 


// 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?

1
  • Besides the below, you will also need to get rid of this. from this.formatChart[k]. this refers to your formatString function Commented Jul 13, 2011 at 19:05

8 Answers 8

4

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

No, the replace method doesn't work with regular expressions if you use a string as the first parameter. Besides, if you are using split and join instead, you should not loop.
I'm looping because the OP wants to replace severals substrings in his string.
When you have replaced a substring, it doesn't exist in the string any more, so you don't have to loop to try to replace it again.
Ho yes, that's true ! I just copied the structure of the question but you are right. I'll edit my answer according to that.
2

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; 
}; 

3 Comments

That will result in an eternal loop, as the value of str never changes.
What do you mean? The statement str = str.replace(k, formatChart[k]); modifies str, doesn't it? Also, it doesn't loop when I test it.
The code was string = str.replace(k, formatChart[k]); when I wrote the comment.
1

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.

2 Comments

I'm curious why you say you shouldn't iterate over an object (assuming hasOwnProperty is used) - how else do you traverse a (pseudo) associative array in JavaScript?
for ... in loops are only bad for built-in objects, in my opinion. This is because built-ins have many extra unwanted properties. For example, Arrays have lengths. For user-made hashtables, on the other hand, it is invaluable. You know what you put in there, and as long as you don't extend Object.prototype, you won't have any extra properties. Note that that particular problem, as tomfumb mentioned, can be fixed with hasOwnProperty.
1

Instead of this:

while (string.indexOf(formatChart[k]) != -1)

Try this:

while (string.indexOf(k) != -1)

Comments

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

Comments

1

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\\]' : '&nbsp;&nbsp;&nbsp;&nbsp;', 
    '\\[space\\]' : '&nbsp;'
};

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/

Comments

0

Here's a fiddle using regex: http://jsfiddle.net/msTuC/

Comments

0

Incorrect: while (string.indexOf(formatChart[k]) != -1)

Correct: while (string.indexOf(k) != -1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.