Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Created June 21, 2014 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pascalduez/065e560c6314c7e9d7f8 to your computer and use it in GitHub Desktop.
Save pascalduez/065e560c6314c7e9d7f8 to your computer and use it in GitHub Desktop.
JS String.prototype.split() in Sass.
// ----
// 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));
}
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