Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am not sure the square brackets are correct (although it has not yet failed some simple tests). I would also like to reduce and simplify this code to one line if practical. I think the code is self explanatory.

  str = str.replace(/[\n]/g,'<br>')
  str = str.replace(/[\t]/g,'&nbsp;&nbsp;&nbsp;&nbsp;')
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

The square brackets are technically correct, but unneeded:

str = str.replace(/\n/g, "<br>");

Also, since a new string is returned, you can chain the methods:

str = str.replace(/\n/g, "<br>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");

For more information, you can read the MDN pages on replace and regular expressions.


Though the above is one line, if wanted to combine it into one replace, you could, but in my opinion this is uglier and less clear:

str.replace(/(\n|\t)/g, function (s) { return (s === "\n" ? "<br>" : "&nbsp;&nbsp;&nbsp;&nbsp;"); });

This could be useful though if you had a large set of simple replacements:

var map = {"\n": "<br>", "\t": "&nbsp;&nbsp;&nbsp;&nbsp;"};
str.replace(/(\n|\t)/g, function (s) { return map[s]; });

The idea could be extended farther to automatically generate the regex instead of relying on changing it every time map is updated.

share|improve this answer
 
I agree. I like the chained example. Thanks for clarifying the square brackets. I like the last example too, I think I have seen something similar. –  John R Jun 11 '12 at 3:20
 
Since you don't actually need regular expressions here, I would do it this way: str = str.split('\n').join('<br>').split('\t').join('&nbsp;&nbsp;&nbsp;&nbsp;') –  Bill Barry Jun 11 '12 at 12:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.