Created
June 21, 2014 13:19
-
-
Save pascalduez/065e560c6314c7e9d7f8 to your computer and use it in GitHub Desktop.
JS String.prototype.split() in Sass.
This file contains 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
// ---- | |
// Sass (v3.3.8) | |
// Compass (v1.0.0.alpha.19) | |
// ---- | |
// String split | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split | |
// Splits a String into a list of substrings using `$separator`. | |
// If separator is omitted, the list returned contains one element consisting of the entire string. | |
// If separator is an empty string, str is converted to a list of all characters. | |
// Integer specifying a limit on the number of splits to be found. | |
// The split method still splits on every match of separator, but it truncates the returned list to at most limit elements. | |
// -------- | |
// @param [string] $str | |
// @param [string] $separator | |
// @param [$number] $limit | |
// -------- | |
// @return [list] | |
@function str-split( | |
$str, | |
$separator: null, | |
$limit: null | |
) { | |
$result: zip(()); | |
@if not $separator { | |
@return ($str,); | |
} | |
@if $separator == '' { | |
@for $i from 1 through str-length($str) { | |
$result: append($result, str-slice($str, $i, $i)); | |
} | |
@return $result; | |
} | |
$running: true; | |
$progress: $str; | |
$length: str-length($separator); | |
@while $running { | |
$index: str-index($progress, $separator); | |
@if $index { | |
$result: append($result, str-slice($progress, 1, ($index - 1))); | |
$progress: str-slice($progress, ($index + $length)); | |
} | |
@else { | |
$running: false; | |
} | |
} | |
$result: append($result, $progress); | |
@if $limit and $limit > 0 { | |
$limit: if($limit > length($result), length($result), $limit); | |
$return: (); | |
@for $i from 1 through $limit { | |
$return: append($return, nth($result, $i)); | |
} | |
@return $return; | |
} | |
@return $result; | |
} | |
tests { | |
$str: 'Hello Berlin !'; | |
t: inspect(str-split($str)); | |
t: inspect(str-split($str, '')); | |
t: inspect(str-split($str, ' ')); | |
t: inspect(str-split($str, ' ', 1)); | |
} |
This file contains 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
tests { | |
t: ("Hello Berlin !",); | |
t: "H", "e", "l", "l", "o", " ", "B", "e", "r", "l", "i", "n", " ", "!"; | |
t: "Hello", "Berlin", "!"; | |
t: "Hello"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment