Monday, September 9, 2013

Javascript replace all line breaks in a string with

  1. str = str.replace('\n', '<br />');  -> However, this only replace the first ocurrence
  2. str = str.replace(/\n/g, '<br />'); -> use regexp to do global match
  3. str.replace(new RegExp('\n','g'), '<br />') -> similar to #2, but use constructor to build RegExp
  4. str = str.split("\n").join("<br />"); -> split and join, another way to do replace
  5. String.prototype.replaceAll = function(needle, replacement) {return this.split(needle).join(replacement||"");}; -> similar to #4, but added to String prototype
Btw, probably we need take care of \r\n case.

No comments:

Post a Comment