Created
April 28, 2012 15:28
-
-
Save jamierumbelow/2519816 to your computer and use it in GitHub Desktop.
JavaScript's .split() being stupid
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
# Let's say we have an email message body with some headers and then the email | |
# content. Just like HTTP, headers\n\nbody | |
string = "Header: here\n\nHere is an email\n\nwith some line breaks\n\nand stuff" | |
# What you'd expect (what PHP's explode() does) | |
string.split("\n\n", 2) == [ "Header: here", "Here is an email\n\nwith some line breaks\n\nand stuff" ] # false | |
# What you actually get | |
string.split("\n\n", 2) == [ "Header: here", "Here is an email" ] # true | |
# In order to get what we need (that is to say, to get the full string | |
# after the first \n\n, ignoring any remaining \n\ns), we need to implement | |
# our own explode() equivalent: | |
String::explode = (delimiter, limit) -> | |
splitted = this.split(delimiter) | |
array = splitted.splice 0, limit - 1 | |
superfluous = splitted.join delimiter | |
array.push superfluous | |
array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment