# StringUnit

**StringUnit** is a type of [Unit](https://docs.activejs.dev/activejs/fundamentals/units) that only accepts `string` data type as its value. It ensures that at any point of time the value would always be `string`.

It implements all the [String.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) methods available in the environment/browser, including polyfills.\
e.g.: `trim`, `includes` and `toLowerCase`, etc., and redirects them to the stored `string` value inside the Unit, so when you call `Unit.includes()` , it'll be executed on the Unit's value instead of the Unit instance itself.&#x20;

When we use `String.prototype` methods like `replace`, it doesn't mutate the value of the Unit, similar to how simple `String.prototype.replace` works.

See [API reference](https://api.activejs.dev/classes/stringunit) for more details.

|                 |                     |
| --------------- | ------------------- |
| Default value   | `''` (empty string) |
| Value data type | `string`            |

### StringUnit vs `string`

StringUnit can not be used as a drop-in replacement for primitive `string` value, since StringUnit is a non-primitive data structure, and the actual `string` value is stored inside the Unit, which can be accessed via`Unit.value()` method. See the below comparisons for more clarity.

```typescript
// initialization
let str = 'Hello';
const unit = new StringUnit({initialValue: 'Hello'});

str === unit // false
str === unit.value() // true

unit + ' World' // 'Hello World'
unit + 1 // 'Hello1'
unit.dispatch('6');
parseInt(unit) // 6

typeof str === 'string' // true
typeof unit === 'object' // true
typeof unit.value() === 'string' // true

// value assignment
str = 'bye';
unit.dispatch('bye');

// value access
console.log(str) // logs 'bye'
console.log(unit.value()) // logs 'bye'
// OR
unit.subscribe(value => console.log(value)) // logs 'bye', will log future values
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.activejs.dev/activejs/fundamentals/units/stringunit.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
