Last active
December 14, 2015 18:19
-
-
Save piercemoore/5128835 to your computer and use it in GitHub Desktop.
Trim ALL tabs, newlines, and unnecessary whitespace from a string in Javascript, simple extension to the String prototype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // For the purposes of this gist, assume we have declared the variable str and it is actually a string. | |
| var str = "This is my awesome string. \n I love strings. \n\t\t\t Stringy string string! \n\t\t\t\tWhat??"; | |
| // Regex to remove all tabs and newlines. | |
| str = str.replace(/[\t]|[\n]/gm, ''); | |
| // Regex to replace all sets of 2 or more space characters with a single space | |
| str = str.replace(/\s{2,}/g, ' '); | |
| // Regex to remove all HTML comments | |
| str = str.replace(/<!--(.*?)-->/gm, ""); | |
| // And a wrapper method that extends the String prototype method and does it all for you. | |
| String.prototype.trim = function() { | |
| return this.replace(/<!--(.*?)-->/gm, "").replace(/[\t]|[\n]/gm, '').replace(/\s{2,}/g, ' '); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment