---
title: String
project: jComponent V19
version: 19.194
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v19/19-194/reference/string/
updated: 2026-11-18T13:58:29.465Z
---

# String

> Methods that jComponent adds to String.prototype for formatting, parsing, validating and converting text.

jComponent adds these methods to `String.prototype`, so they are available on every string as soon as the library is loaded. Numbers and dates have their own helpers on the [Number](../number/) and [Date](../date/) pages, and [Templates with Tangular](../../guides/tangular/) explains the template syntax used by `render()`.

## API

### str.arg(obj, [encode], [def])

Type: `method`

Replaces `{key}` and `{{ key }}` placeholders with values read from an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The source of the values. |
| `encode` | `Boolean, String or Function` | no |  | How the values are encoded. |
| `def` | `String` | no |  | The text used for placeholders without a value. |

Returns: `String` The text with the values applied.

A key can be a nested path such as `{user.name}`. A placeholder without a value stays in the text, unless `def` is set. `args()` is another name for the same method.

The `encode` argument changes how values are written:

| Value | Result |
| --- | --- |
| `true` | The value is URL-encoded. |
| `'escape'` | The value is HTML-encoded. Every placeholder must have a value. |
| `'json'` | The value is written as JSON. Every placeholder must have a value. |
| Function | `function(value, key)` returns the text to write. |

Example: Placeholders
```js
'Hello {name}, {age}'.arg({ name: 'Ann', age: 30 }); // "Hello Ann, 30"
'Hello {{ user.name }}'.arg({ user: { name: 'Ann' } }); // "Hello Ann"
'Hello {name}'.arg({}); // "Hello {name}"
'Hello {name}'.arg({}, undefined, 'guest'); // "Hello guest"
```

Example: Encoding
```js
'/search?q={q}'.arg({ q: 'a b&c' }, true); // "/search?q=a%20b%26c"
'<b>{name}</b>'.arg({ name: '<i>' }, 'escape'); // "<b>&lt;i&gt;</b>"
'data={value}'.arg({ value: { id: 1 } }, 'json'); // "data={\"id\":1}"
'{price}'.arg({ price: 2 }, (value, key) => key + '=' + (value * 2)); // "price=4"
```

### str.COMPILABLE()

Type: `method`

Checks whether an HTML string contains a binding attribute or a component declaration.

Returns: `Boolean` `true` when the text contains one of them.

The method looks for the attributes `data--`, `data---`, `data-import`, `-bind` and `bind`, and for a `COMPONENT(` call.

Example: Check a template
```js
'<div data-bind="user.name"></div>'.COMPILABLE(); // true
'<div>Hello</div>'.COMPILABLE(); // false
```

### str.encode()

Type: `method`

Encodes the characters `<`, `>`, `&` and `"` as HTML entities.

Returns: `String` The encoded text.

Example: Encode text
```js
'<a href="#">Tom & Ann</a>'.encode(); // "&lt;a href=&quot;#&quot;&gt;Tom &amp; Ann&lt;/a&gt;"
```

### str.env()

Type: `method`

Replaces `[key]` with a value from `ENV()` and `[.path]` with a value from the model.

Returns: `String` The text with the values applied.

A key without a value stays in the text.

Example: Read environment values
```js
ENV('site', 'Docs');
SET('common.title', 'Hello');
'[site] page'.env(); // "Docs page"
'[.common.title] page'.env(); // "Hello page"
'[missing] page'.env(); // "[missing] page"
```

### str.flags([path], [value], [type])

Type: `method`

Removes `@flag` words from the text and emits an event for each of them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | The first argument of the event. |
| `value` | `Object` | no |  | The second argument of the event. |
| `type` | `Number or String` | no |  | The third argument of the event. |

Returns: `String` The text without the flags.

Each flag emits the event `@flag name` with the arguments `path`, `value` and `type`. The [Flags and path modifiers](../../guides/flags/) guide explains how flags are used.

Example: Remove flags
```js
ON('@flag hidden', function(path, value, type) {
	console.log('flag', path, value, type);
});

var path = 'user.name @hidden'.flags('user.name', 'Ann', 1);
console.log(path);
```

### str.format(a, [b], [c], ...)

Type: `method`

Replaces the positional placeholders `{0}`, `{1}` and so on with the arguments.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `a` | `Object` | yes |  | The value for `{0}`. Each further argument fills the next position. |

Returns: `String` The formatted text.

A missing or `null` argument writes an empty text. An array is joined without a separator.

Example: Positional values
```js
'{0} and {1}'.format('Ann', 'Bob'); // "Ann and Bob"
'{0}-{1}-{2}'.format('a', null, ['x', 'y']); // "a--xy"
```

### str.isEmail()

Type: `method`

Checks whether the text is an email address.

Returns: `Boolean` `true` for a valid address.

Example: Validate an address
```js
'ann@example.com'.isEmail(); // true
'ann@example'.isEmail(); // false
```

### str.isJSONDate()

Type: `method`

Checks whether the text has the shape of a date serialized to JSON.

Returns: `Boolean` `true` when the text has the shape `yyyy-MM-ddTHH:mm:ss.sssZ`.

The method checks the length and the positions of the separators, and the final `Z`. It does not validate the values.

Example: Detect a JSON date
```js
'2026-11-18T10:20:30.000Z'.isJSONDate(); // true
'2026-11-18'.isJSONDate(); // false
```

### str.isPhone()

Type: `method`

Checks whether the text is a phone number.

Returns: `Boolean` `true` for a valid number.

The number has an optional `+`, a group of three digits that can be in parentheses, a group of three digits and a group of four to eight digits. The groups can be separated by a single space, `-` or `.`.

Example: Validate a number
```js
'+421903123456'.isPhone(); // true
'123-456-7890'.isPhone(); // true
'12345'.isPhone(); // false
```

### str.isURL()

Type: `method`

Checks whether the text is an `http` or `https` address.

Returns: `Boolean` `true` for a valid address.

Example: Validate an address
```js
'https://www.totaljs.com'.isURL(); // true
'ftp://example.com/file'.isURL(); // false
'totaljs.com'.isURL(); // false
```

### str.padLeft(length, [char])

Type: `method`

Adds a character to the left side until the text reaches a length.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | The final length. |
| `char` | `String` | no | `' '` | The character to add. |

Returns: `String` The padded text.

Text that is already long enough is returned unchanged.

Example: Pad on the left
```js
'5'.padLeft(3, '0'); // "005"
'5'.padLeft(3); // "  5"
'hello'.padLeft(3, '0'); // "hello"
```

### str.padRight(length, [char])

Type: `method`

Adds a character to the right side until the text reaches a length.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | The final length. |
| `char` | `String` | no | `' '` | The character to add. |

Returns: `String` The padded text.

Text that is already long enough is returned unchanged.

Example: Pad on the right
```js
'5'.padRight(3, '-'); // "5--"
```

### str.parseConfig([def], [callback])

Type: `method`

Parses a `key:value;key:value` text into an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `String, Object or Function` | no |  | Default values as a configuration text or an object. A function is used as `callback`. |
| `callback` | `Function` | no |  | `function(key, value)` is called for each parsed pair. |

Returns: `Object` The parsed configuration.

The values `true` and `false` become booleans and numeric values become numbers. Use `\:` and `\;` to write these characters in a value; the colon of an `http://`, `https://`, `ws://` or `wss://` address needs no escaping. Keys and values go through [env()](#env). A pair with more than one unescaped colon is skipped.

When `def` is an object, the values are written to that object and the same object is returned.

Example: Parse a configuration
```js
'title:Hello;limit:10;visible:true'.parseConfig(); // {"title":"Hello","limit":10,"visible":true}
'url:https://www.totaljs.com;size:2'.parseConfig(); // {"url":"https://www.totaljs.com","size":2}
```

Example: Default values and a callback
```js
'limit:10'.parseConfig('limit:5;page:1'); // {"limit":10,"page":1}

var keys = [];
'a:1;b:2'.parseConfig((key, value) => keys.push(key + '=' + value));
keys; // ["a=1","b=2"]
```

### str.parseDate([format])

Type: `method`

Converts the text to a `Date`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | The layout of the text. |

Returns: `Date` The parsed date, or `null` for an empty text.

Without `format`, the method reads `yyyy-MM-dd` and `dd.MM.yyyy`, optionally followed by a time in the form `HH:mm` or `HH:mm:ss`, separated by a space or `T`. A text ending with `Z` is read as a UTC date. Any other text goes to the `Date` constructor. A time alone uses the current date.

With `format`, the digits of the text are read by position, so each value must have the width of its token. The supported tokens are `yyyy`, `yy`, `MM`, `dd`, `HH`, `mm` and `ss`. A two-digit year is added to 2000. The format must contain the day.

Example: Automatic detection
```js
'2026-11-18 14:05:09'.parseDate().format('dd.MM.yyyy HH:mm:ss'); // "18.11.2026 14:05:09"
'18.11.2026'.parseDate().format('yyyy-MM-dd'); // "2026-11-18"
'2026-11-18T13:05:09.000Z'.parseDate().getTime() === Date.UTC(2026, 10, 18, 13, 5, 9); // true
''.parseDate(); // null
```

Example: A custom layout
```js
'18/11/2026'.parseDate('dd/MM/yyyy').format('yyyy-MM-dd'); // "2026-11-18"
'20261118'.parseDate('yyyyMMdd').format('yyyy-MM-dd'); // "2026-11-18"
'18.11.26 14:05'.parseDate('dd.MM.yy HH:mm').format('yyyy-MM-dd HH:mm'); // "2026-11-18 14:05"
```

### str.parseEncoded()

Type: `method`

Parses a URL query string into an object.

Returns: `Object` The parsed values.

Everything up to the `?` and everything after the `#` is ignored. Keys and values are decoded with `decodeURIComponent()`, and all values stay strings.

Example: Read a query string
```js
'name=Ann&city=New%20York'.parseEncoded(); // {"name":"Ann","city":"New York"}
'/products/?page=2&sort=asc#top'.parseEncoded(); // {"page":"2","sort":"asc"}
```

### str.parseExpire()

Type: `method`

Converts a duration such as `5 minutes` to milliseconds.

Returns: `Number` The duration in milliseconds.

The text has a number, a space and a unit. An unknown unit returns `0`, and so does a text that does not start with a number.

| Unit | Accepted names |
| --- | --- |
| Seconds | `seconds`, `second`, `sec`, `ss`, `s` |
| Minutes | `minutes`, `minute`, `min`, `mm`, `m` |
| Hours | `hours`, `hour`, `HH`, `hh`, `h`, `H` |
| Days | `days`, `day`, `DD`, `dd`, `d` |
| Weeks | `weeks`, `week`, `W`, `w` |
| Months (28 days) | `months`, `month`, `MM`, `M` |
| Years (365 days) | `years`, `year`, `yyyy`, `yy`, `y` |

Example: Durations
```js
'30 seconds'.parseExpire(); // 30000
'5 minutes'.parseExpire(); // 300000
'1 day'.parseExpire(); // 86400000
'1 month'.parseExpire(); // 2419200000
'none'.parseExpire(); // 0
```

### str.parseFloat([def])

Type: `method`

Reads the first decimal number from the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when the text has no valid number. |

Returns: `Number` The parsed number.

The decimal separator can be a dot or a comma. A number that contains both of them, such as `1,234.5`, is not valid and returns the default value.

Example: Read a decimal number
```js
'12.5'.parseFloat(); // 12.5
'12,5'.parseFloat(); // 12.5
'-3.25 kg'.parseFloat(); // -3.25
'abc'.parseFloat(1.5); // 1.5
```

### str.parseInt([def])

Type: `method`

Reads the first whole number from the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value returned when the text has no number. |

Returns: `Number` The parsed number.

Example: Read a whole number
```js
'123abc'.parseInt(); // 123
' -42 '.parseInt(); // -42
'a12b3'.parseInt(); // 12
'abc'.parseInt(7); // 7
```

### str.parseSource([type])

Type: `method`

Parses an `id|name|icon` list into an array of objects.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `Number or String` | no |  | Use `Number` or `'number'` to convert identifiers to numbers. |

Returns: `Array` Objects with the fields `id`, `name` and `icon`.

Items are separated by commas. The name defaults to the identifier and the icon to an empty text.

Example: Parse a list
```js
'1|One|ti ti-star,2|Two'.parseSource(); // [{"id":"1","name":"One","icon":"ti ti-star"},{"id":"2","name":"Two","icon":""}]
'1|One,2'.parseSource(Number); // [{"id":1,"name":"One","icon":""},{"id":2,"name":"2","icon":""}]
```

### str.removeTags()

Type: `method`

Removes HTML tags from the text.

Returns: `String` The text without tags.

Everything from a `<` to the next `>` is treated as a tag.

Example: Strip HTML
```js
'<p>Hello <b>world</b></p>'.removeTags(); // "Hello world"
```

### str.render(model, [repository])

Type: `method`

Compiles the text as a Tangular template and renders it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | The data of the template. |
| `repository` | `Object` | no |  | Additional data, available in the template as `$`. |

Returns: `String` The rendered output.

The [Templates with Tangular](../../guides/tangular/) guide describes the syntax.

Example: Render a template
```js
'Hello {{ name }}'.render({ name: '<Ann>' }); // "Hello &lt;Ann&gt;"
'{{ $.title }}: {{ name }}'.render({ name: 'Ann' }, { title: 'User' }); // "User: Ann"
```

### str.ROOT([nobase])

Type: `method`

Prepends `DEF.root` or `DEF.baseurl` to a relative URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `nobase` | `Boolean` | no |  | Use `true` to ignore `DEF.baseurl`. |

Returns: `String` The final URL.

`DEF.root` is used when it is set; otherwise `DEF.baseurl` is used. Both can be a string or a function that receives the URL and returns the new one. A string prefix is not added to an absolute URL. Repeated slashes in the result are reduced to one. See [DEF](../def/).

Example: Prefix a URL
```js
DEF.root = '/app';
'/users/'.ROOT(); // "/app/users/"
'https://www.totaljs.com/'.ROOT(); // "https://www.totaljs.com/"
DEF.root = '';

DEF.baseurl = '/base';
'/users/'.ROOT(); // "/base/users/"
'/users/'.ROOT(true); // "/users/"
DEF.baseurl = '';
```

### str.SCOPE(element)

Type: `method`

Replaces `?` in a path with the path of the scope of an element.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `Element, jQuery, Component, Plugin or Scope` | yes |  | The object that gives the scope. |

Returns: `String` The final path.

A path without `?` is returned as it is. See [Scopes](../../guides/scopes/).

Example: Resolve a scoped path
```html
<ui-plugin path="orders"><div id="field"></div></ui-plugin>

<script>
PLUGIN('orders', function(exports) {});

setTimeout(function() {
	var path = '?.name'.SCOPE($('#field'));
	console.log(path);
}, 500);
</script>
```

### str.slug([max])

Type: `method`

Converts the text to a lowercase, URL-friendly identifier.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `60` | The maximum length. |

Returns: `String` The slug.

Diacritics are converted with [toASCII()](#toascii). Spaces and punctuation become a single `-`, and characters without an ASCII form are removed.

Example: Create a slug
```js
'Hello World!'.slug(); // "hello-world"
'  Žluťoučký kůň  '.slug(); // "zlutoucky-kun"
'one two three'.slug(7); // "one-two"
```

### str.toASCII()

Type: `method`

Replaces diacritical characters with their ASCII letters.

Returns: `String` The converted text.

The conversion covers the characters `á ä č ď é ě í ï ĺ ľ ň ó ô ö ő ŕ ř š ť ú ů ü ű ý ÿ ž ć` in both cases. Other characters stay unchanged.

Example: Remove diacritics
```js
'Žluťoučký kůň'.toASCII(); // "Zlutoucky kun"
'Señor'.toASCII(); // "Señor"
```

### str.toSearch()

Type: `method`

Normalizes the text for fuzzy searching.

Returns: `String` The normalized text.

The method removes punctuation except the colon, converts the text to lowercase ASCII, replaces `y` with `i` and collapses repeated characters.

Example: Normalize a search term
```js
'Žluťoučký Kůň!'.toSearch(); // "zlutoucki kun"
'Yellow Sunny'.toSearch(); // "ielow suni"
```

### str.VARIABLES([args])

Type: `method`

Reads `--name=value--` definitions from the text and replaces `--name--` placeholders.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `args` | `Object` | no |  | Predefined values. Definitions found in the text are added to this object. |

Returns: `String` The processed text.

Definitions are removed from the text and stored in `args`. A placeholder without a value stays in the text.

Example: Variables in a text
```js
'--color=red--Color: --color--'.VARIABLES(); // "Color: red"
'Size: --size--'.VARIABLES({ size: '10px' }); // "Size: 10px"
'Size: --size--'.VARIABLES(); // "Size: --size--"
```
