// Use.
@use '@angular-package/sass/string';
// Examples.
// single replacement first occurrence
@debug string.replace('bold king is hairy', first, 'bold', 'baloon'); // baloon king is hairy
@debug string.replace('bold king is hairy', first, 'bold', ''); // king is hairy
@debug string.replace(':==', first, ':', '');
// single replacement all occurrences
@debug string.replace('bold king is hairy', all, 'bold', 'baloon'); // baloon king is hairy
@debug string.replace('bold king is hairy', all, 'king', 'baloon'); // baloon king is hairy
@debug string.replace('bold king is bold hairy', all, 'bold', ''); // king is hairy
@debug string.replace('bold king is bold hairy', all, 'bold', 'test'); // test king is test hairy
// multiple replacements
@debug string.replace('bold king is hairy', all, ('bold', 'king'), 'baloon'); // baloon king is hairy
@debug string.replace('bold king is hairy', first, (bold is), ''); // king hairy
// 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