string.replace()

The string.replace() function replaces the first or all $substring occurrences in the string with $replacement.

// Modules.
@use 'string.replace.function';

// The `string.replace()` function.
@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;
}

Parameters

$string

A string to replace first or all $substring in it by $replacement.

$occurrence

First or all occurrences of $substring to replace in $string.

$substring

A string or list of strings to replace by $replacement.

$replacement

A string to replace $substring.

Return

The return value is a string with a first/all replaced $substring by $replacement.

Examples

// 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

Last updated