Spanish Total.js
English
Documentation For AI agents
Contents

String

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

.md GitHub
On this page

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 and Date pages, and Templates with Tangular explains the template syntax used by render().

API

method

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

Replaces {key} and {{ key }} placeholders with values read from an object.
ParameterTypeDescription
obj Object The source of the values.
encode? Boolean, String or Function How the values are encoded.
def? String 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:

ValueResult
trueThe 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.
Functionfunction(value, key) returns the text to write.
Placeholders
'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"
Encoding
'/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"
method

str.COMPILABLE()

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.

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

str.encode()

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

Returns String The encoded text.

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

str.env()

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.

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

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

Removes @flag words from the text and emits an event for each of them.
ParameterTypeDescription
path? String The first argument of the event.
value? Object The second argument of the event.
type? Number or String 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 guide explains how flags are used.

Remove flags
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);
method

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

Replaces the positional placeholders {0}, {1} and so on with the arguments.
ParameterTypeDescription
a Object 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.

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

str.isEmail()

Checks whether the text is an email address.

Returns Boolean true for a valid address.

Validate an address
'ann@example.com'.isEmail(); // true
'ann@example'.isEmail(); // false
method

str.isJSONDate()

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.

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

str.isPhone()

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

Validate a number
'+421903123456'.isPhone(); // true
'123-456-7890'.isPhone(); // true
'12345'.isPhone(); // false
method

str.isURL()

Checks whether the text is an http or https address.

Returns Boolean true for a valid address.

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

str.padLeft(length, [char])

Adds a character to the left side until the text reaches a length.
ParameterTypeDescription
length Number The final length.
char? String The character to add. Default: ' '

Returns String The padded text.

Text that is already long enough is returned unchanged.

Pad on the left
'5'.padLeft(3, '0'); // "005"
'5'.padLeft(3); // "  5"
'hello'.padLeft(3, '0'); // "hello"
method

str.padRight(length, [char])

Adds a character to the right side until the text reaches a length.
ParameterTypeDescription
length Number The final length.
char? String The character to add. Default: ' '

Returns String The padded text.

Text that is already long enough is returned unchanged.

Pad on the right
'5'.padRight(3, '-'); // "5--"
method

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

Parses a key:value;key:value text into an object.
ParameterTypeDescription
def? String, Object or Function Default values as a configuration text or an object. A function is used as callback.
callback? Function 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(). 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.

Parse a configuration
'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}
Default values and a callback
'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"]
method

str.parseDate([format])

Converts the text to a Date.
ParameterTypeDescription
format? String 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.

Automatic detection
'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
A custom layout
'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"
method

str.parseEncoded()

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.

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

str.parseExpire()

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.

UnitAccepted names
Secondsseconds, second, sec, ss, s
Minutesminutes, minute, min, mm, m
Hourshours, hour, HH, hh, h, H
Daysdays, day, DD, dd, d
Weeksweeks, week, W, w
Months (28 days)months, month, MM, M
Years (365 days)years, year, yyyy, yy, y
Durations
'30 seconds'.parseExpire(); // 30000
'5 minutes'.parseExpire(); // 300000
'1 day'.parseExpire(); // 86400000
'1 month'.parseExpire(); // 2419200000
'none'.parseExpire(); // 0
method

str.parseFloat([def])

Reads the first decimal number from the text.
ParameterTypeDescription
def? Number The value returned when the text has no valid number. Default: 0

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.

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

str.parseInt([def])

Reads the first whole number from the text.
ParameterTypeDescription
def? Number The value returned when the text has no number. Default: 0

Returns Number The parsed number.

Read a whole number
'123abc'.parseInt(); // 123
' -42 '.parseInt(); // -42
'a12b3'.parseInt(); // 12
'abc'.parseInt(7); // 7
method

str.parseSource([type])

Parses an id|name|icon list into an array of objects.
ParameterTypeDescription
type? Number or String 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.

Parse a list
'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":""}]
method

str.removeTags()

Removes HTML tags from the text.

Returns String The text without tags.

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

Strip HTML
'<p>Hello <b>world</b></p>'.removeTags(); // "Hello world"
method

str.render(model, [repository])

Compiles the text as a Tangular template and renders it.
ParameterTypeDescription
model Object The data of the template.
repository? Object Additional data, available in the template as $.

Returns String The rendered output.

The Templates with Tangular guide describes the syntax.

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

str.ROOT([nobase])

Prepends DEF.root or DEF.baseurl to a relative URL.
ParameterTypeDescription
nobase? Boolean 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.

Prefix a URL
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 = '';
method

str.SCOPE(element)

Replaces ? in a path with the path of the scope of an element.
ParameterTypeDescription
element Element, jQuery, Component, Plugin or Scope The object that gives the scope.

Returns String The final path.

A path without ? is returned as it is. See Scopes.

Resolve a scoped path
<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>
method

str.slug([max])

Converts the text to a lowercase, URL-friendly identifier.
ParameterTypeDescription
max? Number The maximum length. Default: 60

Returns String The slug.

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

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

str.toASCII()

Replaces diacritical characters with their ASCII letters.

Returns String The converted text.

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

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

str.toSearch()

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.

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

str.VARIABLES([args])

Reads --name=value-- definitions from the text and replaces --name-- placeholders.
ParameterTypeDescription
args? Object 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.

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