-
-
Save dcdustin/1015289 to your computer and use it in GitHub Desktop.
| /* | |
| // Modifying global String object version | |
| s=String.prototype; // shortcut for String.prototype | |
| s.nl2br = function(){ // newline to <br> method | |
| return this.replace(/\r?\n/g,'<br>') // replaces all instances of \r\n or \n with a <br> | |
| }; | |
| s.br2nl = function(){ // <br> to new line method | |
| return this.replace(/<br[^>]*>/g,"\n") // replaces all instances of <br> or <br/> or <br /> or <br ...> with \n | |
| } | |
| */ | |
| // 140byt.es version | |
| function(s, // string to work with | |
| n){ // if true replace nl with br, otherwise br with nl | |
| return s.replace( // replace found s values | |
| n?/\r?\n/g:/<br[^>]*>/g, // conditional to test what we are replaceing | |
| n?'<br>':"\n" // what value do we replace with | |
| ) // done | |
| } |
| function(s,n){return s.replace(n?/\r?\n/g:/<br[^>]*>/g,n?'<br>':"\n")} |
| DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
| Version 2, December 2004 | |
| Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE> | |
| Everyone is permitted to copy and distribute verbatim or modified | |
| copies of this license document, and changing it is allowed as long | |
| as the name is changed. | |
| DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
| TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
| 0. You just DO WHAT THE FUCK YOU WANT TO. |
| { | |
| "name": "nl2Br2Nl", | |
| "description": "Expression for replacing new line characters and HTML line breaks with one another.", | |
| "keywords": [ | |
| "string", | |
| "newline", | |
| "linebreak" | |
| ] | |
| } |
| <!DOCTYPE html> | |
| <title>nl2br and br2nl</title> | |
| <script> | |
| var n2b2n = function(s,n){return s.replace(n?/\r?\n/g:/<br[^>]*>/g,n?'<br>':"\n")}; | |
| var sOne = "Read\nMy\r\nLips"; | |
| var sTwo = "No<br>New<br />Lines<br/>"; | |
| console.log(sOne + "\n\n" + n2b2n(sOne, 1)); | |
| console.log(sTwo + "\n\n" + n2b2n(sTwo)); | |
| </script> |
i consider it leaking only when the change in global scope is a side-effect, which it's not in this case.
(that said, i'm not a huge fan of extending global prototypes)
I agree if the extending is as explicit as it is here, it should be ok.
btw, if you combine both functions into one you can save a whole lot of bytes.
Hey guys, thanks for the comments. I left them separate to somewhat follow the PHP structuring of nl2br (even though PHP doesn't have a br2nl, weird, eh?). Also I thought they were much more useful as string methods than as an assignable expression. However, if you prefer them as the latter, I'll do so for the purposes of 140byt.es.
I just went ahead and modified it with the suggestions you guys had, but left the String prototype version commented into the annotated version for posterity reasons. ^_^
You can replace <br[^>]*> with <br.*?>
does adding methods to built-in datatypes as leak to the global scope ? @jed