-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_string.replace.function.scss
More file actions
45 lines (41 loc) · 2.01 KB
/
_string.replace.function.scss
File metadata and controls
45 lines (41 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Sass.
@use 'sass:string';
// Status: DONE
// The `string.replace()` function replaces the first or all `$substring` occurrences in the string with `$replacement`.
// @param `$string` A `string` to replace first or all `$substring` in it by `$replacement`.
// @param `$occurrence` First or all occurrences of `$substring` to replace in `$string`.
// @param `$substring` A `string` or list of strings to replace by `$replacement`.
// @param `$replacement` A `string` to replace `$substring`.
// @return The return value is a `string` with a first/all replaced `$substring` by `$replacement`.
@function replace($string, $occurrence, $substring, $replacement) {
@each $value in $substring {
$index: string.index($string, $value);
@while not ($index == null) {
$string: string.insert(string.slice($string, 1, $index - 1) + string.slice(
$string,
$index + string.length($value),
string.length($string)
), $replacement, $index);
@if $occurrence == first {
$index: null;
}
@if $occurrence == all or ($occurrence == first and not ($index == null)) {
$index: string.index($string, $value);
}
}
}
@return $string;
}
// Examples.
// single replacement first occurrence
// @debug replace('bold king is hairy', first, 'bold', 'baloon'); // baloon king is hairy
// @debug replace('bold king is hairy', first, 'bold', ''); // king is hairy
// @debug replace(':==', first, ':', '');
// single replacement all occurrences
// @debug replace('bold king is hairy', all, 'bold', 'baloon'); // baloon king is hairy
// @debug replace('bold king is hairy', all, 'king', 'baloon'); // baloon king is hairy
// @debug replace('bold king is bold hairy', all, 'bold', ''); // king is hairy
// @debug replace('bold king is bold hairy', all, 'bold', 'test'); // test king is test hairy
// multiple replacements
// @debug replace('bold king is hairy', all, ('bold', 'king'), 'baloon'); // baloon king is hairy
// @debug replace('bold king is hairy', first, (bold is), ''); // king hairy