- str = str.replace('\n', '<br />'); -> However, this only replace the first ocurrence
- str = str.replace(/\n/g, '<br />'); -> use regexp to do global match
- str.replace(new RegExp('\n','g'), '<br />') -> similar to #2, but use constructor to build RegExp
- str = str.split("\n").join("<br />"); -> split and join, another way to do replace
- String.prototype.replaceAll = function(needle, replacement) {return this.split(needle).join(replacement||"");}; -> similar to #4, but added to String prototype
Monday, September 9, 2013
Javascript replace all line breaks in a string with
Labels:
javascript,
regexp,
replace
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment