Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.