# string.replace()

The `string.replace()` function replaces the first or all [`$substring`](#usdsubstring) occurrences in the `string` with [`$replacement`](#usdreplacement).

{% code lineNumbers="true" %}

```scss
// 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;
}
```

{% endcode %}

{% embed url="<https://github.com/angular-package/sass/blob/main/string/_string.replace.function.scss>" %}

### Parameters

#### **`$string`**

A `string` to replace first or all [`$substring`](#usdsubstring) in it by [`$replacement`](#usdreplacement).

#### `$occurrence`

First or all occurrences of [`$substring`](#usdsubstring) to replace in [`$string`](#usdstring).

#### `$substring`

A `string` or list of strings to replace by [`$replacement`](#usdreplacement).

#### `$replacement`

A `string` to replace [`$substring`](#usdsubstring).

### Return

The return value is a `string` with a first/all replaced [`$substring`](#usdsubstring) by [`$replacement`](#usdreplacement).

## Examples

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

```
