Spanish Total.js
English
Documentation For AI agents
Contents

String

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

.md GitHub
On this page

jComponent adds these methods to every string. Number and date output follows the settings in DEF, values in [key] form come from ENV(), and the methods that read component configuration are used in Creating components.

API

method

String.args(obj, [encode])

Replaces {key} and {{ key }} placeholders with values from an object.
ParameterTypeDescription
obj Object The values for the placeholders.
encode? String or Function How to write each value: json for JSON.stringify(), encode for encodeURIComponent(), escape for HTML entities, or a function (value, key) that returns the text.

Returns String The string with the placeholders replaced.

A key can be a nested path such as user.age. Without encode, a key that is not in the object keeps its placeholder and a null value becomes an empty string.

Placeholders
console.log('Hello {name}, age {{ user.age }}, {unknown}'.args({ name: 'Ana', user: { age: 30 } })); // Hello Ana, age 30, {unknown}
Encoding the values
console.log('{a}'.args({ a: '<b>' }, 'escape')); // &lt;b&gt;
console.log('{a}'.args({ a: 'x y' }, 'encode')); // x%20y
console.log('{a}'.args({ a: 'x' }, 'json')); // "x"
console.log('{a}|{b}'.args({ a: 1, b: 2 }, (value, key) => key + '=' + value)); // a=1|b=2
method

String.encode()

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

Returns String The escaped text.

Escaping HTML
console.log('<a href="x">T&C</a>'.encode()); // &lt;a href=&quot;x&quot;&gt;T&amp;C&lt;/a&gt;
method

String.env()

Replaces [key] phrases with values from the environment.

Returns String The string with the known phrases replaced.

A [key] phrase reads the value set with ENV(). A phrase that starts with a dot, such as [.app.name], reads a path from window. A phrase with no value stays in the text.

Environment values
ENV('name', 'Peter');
window.app = { version: 5 };
console.log('[name] [.app.version] [missing]'.env()); // Peter 5 [missing]
method

String.flags([path])

Removes @name flags from the text and emits an event for each flag that has a listener.
ParameterTypeDescription
path? String The value passed to the event listeners.

Returns String The trimmed text without the flags.

Each flag emits the event @flag name with path as its argument. See Flags and path modifiers.

Reading flags
var seen = [];
ON('@flag reset', path => seen.push(path));
console.log('form.name @reset @other'.flags('form.name')); // form.name
console.log(seen); // ["form.name"]
method

String.format([value0], [value1], [...])

Replaces the indexes {0}, {1} and so on with the arguments.
ParameterTypeDescription
value0? Object The value for {0}. Each further argument fills the next index.

Returns String The formatted text.

An array argument is joined without a separator. A missing or null argument becomes an empty string.

Indexed values
console.log('Hello {0}, you have {1} items{2}'.format('Ana', 3)); // Hello Ana, you have 3 items
console.log('{0}'.format(['a', 'b'])); // ab
method

String.isEmail()

Checks that the string is an email address.

Returns Boolean true for a valid address.

The test uses the pattern in DEF.regexp.email.

Checking addresses
console.log('peter+news@total-js.com'.isEmail()); // true
console.log('a@b'.isEmail()); // false
method

String.isJSONDate()

Checks that the string is a date serialized to JSON.

Returns Boolean true for a value in the form 2026-11-18T10:00:00.000Z.

Checking dates
console.log('2026-11-18T10:00:00.000Z'.isJSONDate()); // true
console.log('2026-11-18'.isJSONDate()); // false
method

String.isPhone()

Checks that the string is a phone number.

Returns Boolean true for a valid number.

The test uses the pattern in DEF.regexp.phone: an optional +, then groups of three, three and four to eight digits. The groups can be separated by a space, a dash or a dot, and the first can be in parentheses.

Checking numbers
console.log('+421903123456'.isPhone()); // true
console.log('(421) 903-1234'.isPhone()); // true
console.log('12345'.isPhone()); // false
method

String.isURL()

Checks that the string is an http or https address.

Returns Boolean true for a valid address.

The test uses the pattern in DEF.regexp.url.

Checking addresses
console.log('https://www.totaljs.com/'.isURL()); // true
console.log('ftp://totaljs.com/file'.isURL()); // false
console.log('totaljs.com'.isURL()); // false
method

String.padLeft(length, [char])

Fills the start of the string up to a length.
ParameterTypeDescription
length Number The final length.
char? String The fill character. Default: a space

Returns String The padded text.

A string that is already long enough is returned unchanged.

Padding
console.log('7'.padLeft(3, '0')); // 007
console.log('abcd'.padLeft(2, '0')); // abcd
method

String.padRight(length, [char])

Fills the end of the string up to a length.
ParameterTypeDescription
length Number The final length.
char? String The fill character. Default: a space

Returns String The padded text.

A string that is already long enough is returned unchanged.

Padding
console.log('7'.padRight(3, '-')); // 7--
method

String.parseComponent(tags)

Extracts the content of HTML tags from a string.
ParameterTypeDescription
tags Object The result keys and their opening tags.

Returns Object The content found for each key.

Each key of tags holds the exact opening tag to look for. Nested tags of the same name stay in the content. A tag that is not found is left out of the result.

Splitting a template
var html = '<style>b { color: red }</style><div>One<div>Two</div></div>';
console.log(html.parseComponent({ css: '<style>', body: '<div>', none: '<nav>' })); // {"css":"b { color: red }","body":"One<div>Two</div>"}
method

String.parseConfig([def], [noconvert])

Parses configuration text in the form key1:value;key2:value.
ParameterTypeDescription
def? String or Object Default configuration that the parsed values extend.
noconvert? Boolean true keeps every value as a string. Default: false

Returns Object The parsed configuration.

Values true and false become booleans and numeric values become numbers. A key without a value gets an empty string. Write \; to keep a semicolon inside a value. Keys and values can contain [key] phrases, which are replaced as in env().

Parsing
console.log('size:12;visible:true;title:Hello'.parseConfig()); // {"size":12,"visible":true,"title":"Hello"}
console.log('size:12'.parseConfig('size:5;color:red')); // {"size":12,"color":"red"}
console.log('size:12;visible:true'.parseConfig(null, true)); // {"size":"12","visible":"true"}
console.log('title:a\\;b;size:1'.parseConfig()); // {"title":"a;b","size":1}
method

String.parseDate([format])

Converts a string to a Date.
ParameterTypeDescription
format? String The layout of the date.

Returns Date The parsed date. An empty string without format returns null, and text that is not a date returns an invalid Date.

Without format the method reads yyyy-MM-dd, dd.MM.yyyy, each of them with an optional time HH:mm:ss or HH:mm:ss.SSS and an optional am or pm, a time alone (which uses the current day) and JSON dates. [key] phrases are replaced first, as in env().

With format the method takes the digits of the string in order and assigns them to the tokens yyyy, yy, MM, dd, HH, hh, mm and ss, so each value must have as many digits as its token. When the string contains am or pm, the hours are read on a 12-hour clock.

Common forms
console.log('2026-11-18 14:30:15'.parseDate().format('dd.MM.yyyy HH:mm:ss')); // 18.11.2026 14:30:15
console.log('18.11.2026 14:30'.parseDate().format('yyyy-MM-dd HH:mm')); // 2026-11-18 14:30
console.log('2026-11-18T10:00:00.000Z'.parseDate().toISOString()); // 2026-11-18T10:00:00.000Z
console.log(''.parseDate()); // null
Custom layout
console.log('18/11/2026'.parseDate('dd/MM/yyyy').format('yyyy-MM-dd')); // 2026-11-18
console.log('11-18-26 14:05'.parseDate('MM-dd-yy HH:mm').format('yyyy-MM-dd HH:mm')); // 2026-11-18 14:05
12-hour times
console.log('2026-11-18 12:30 pm'.parseDate().format('yyyy-MM-dd HH:mm')); // 2026-11-18 12:30
console.log('2026-11-18 12:30 am'.parseDate().format('yyyy-MM-dd HH:mm')); // 2026-11-18 00:30
console.log('18/11/2026 02:30 pm'.parseDate('dd/MM/yyyy hh:mm').format('yyyy-MM-dd HH:mm')); // 2026-11-18 14:30
console.log('2026-11-18 14:30:15.250'.parseDate().getMilliseconds()); // 250
method

String.parseExpire()

Converts a duration such as 5 minutes to milliseconds.

Returns Number The duration in milliseconds.

The string is a number, a space and a unit. A dot in the unit is ignored.

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

An empty string, a number without a unit, text that does not start with a number and an unknown unit return 0.

Durations
console.log('5 minutes'.parseExpire()); // 300000
console.log('1 hour'.parseExpire()); // 3600000
console.log('2 days'.parseExpire()); // 172800000
console.log('none'.parseExpire()); // 0
method

String.parseFloat([def])

Reads a decimal number from the string.
ParameterTypeDescription
def? Number The value returned when the string holds no valid number. Default: 0

Returns Number The parsed number.

The method takes the first number in the text and accepts a dot or a comma as the decimal separator.

Reading numbers
console.log('12,5 kg'.parseFloat()); // 12.5
console.log('-3.25'.parseFloat()); // -3.25
console.log('abc'.parseFloat(1.5)); // 1.5
method

String.parseInt([def])

Reads a whole number from the string.
ParameterTypeDescription
def? Number The value returned when the string holds no digits. Default: 0

Returns Number The parsed number.

The method takes the first group of digits in the text, with its sign.

Reading numbers
console.log('12px'.parseInt()); // 12
console.log('-3.9'.parseInt()); // -3
console.log('abc'.parseInt(5)); // 5
method

String.parseSource([type])

Converts text in the form id|name|icon,id|name to a list of items.
ParameterTypeDescription
type? Function or String Pass Number or 'number' to convert the identifiers to numbers.

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

A missing name uses the identifier and a missing icon is an empty string.

Building a list
console.log('1|One|ti-star,2'.parseSource()); // [{"id":"1","name":"One","icon":"ti-star"},{"id":"2","name":"2","icon":""}]
console.log('1|One'.parseSource(Number)); // [{"id":1,"name":"One","icon":""}]
method

String.ROOT([noBase])

Adds the application root or base URL to an address.
ParameterTypeDescription
noBase? Boolean true ignores DEF.baseurl. Default: false

Returns String The final address.

DEF.root is used first and DEF.baseurl when it is empty. Each of them can be a string or a function that receives the address and returns the result. A string prefix is not added to an absolute address.

Base URL
DEF.baseurl = '/app/';
console.log('/api/users/'.ROOT()); // /app/api/users/
console.log('/api/users/'.ROOT(true)); // /api/users/
console.log('https://www.totaljs.com/'.ROOT()); // https://www.totaljs.com/
method

String.slug([max])

Converts text to a lowercase form for use in an address.
ParameterTypeDescription
max? Number The maximum length. Default: 60

Returns String The slug.

Diacritics are converted with toASCII(). Spaces and most punctuation become a single dash. Letters, digits and underscores stay, and other characters are removed.

Creating slugs
console.log('Hello World! 2026'.slug()); // hello-world-2026
console.log('Hello wonderful world'.slug(8)); // hello-wo
method

String.toASCII()

Replaces accented letters with plain ones.

Returns String The converted text.

The method converts the letters á ä ć č ď é ě í ï ĺ ľ ň ó ô ö ő ŕ ř š ť ú ů ü ű ý ÿ ž and their uppercase forms. Letters keep their case, and other characters stay as they are.

Removing diacritics
console.log('Príliš žluťoučký kůň'.toASCII()); // Prilis zlutoucky kun
console.log('Ťažký ñ'.toASCII()); // Tazky ñ
method

String.toSearch()

Normalizes text for full-text comparison.

Returns String The normalized text.

The method removes punctuation, converts the text to lowercase ASCII, replaces y with i and reduces repeated characters to one.

Normalizing
console.log('Hello Yellow!'.toSearch()); // helo ielow
console.log('Príliš žlté'.toSearch()); // prilis zlte
method

String.VARIABLES([args])

Replaces --key-- variables in the string.
ParameterTypeDescription
args? Object The values of the variables.

Returns String The string with the variables replaced.

A definition in the form --key=value-- is removed from the text and sets the variable for the rest of the string. A variable with no value stays in the text.

Using variables
console.log('--color-- and --size--'.VARIABLES({ color: 'red' })); // red and --size--
console.log('--color=blue--Color: --color--'.VARIABLES()); // Color: blue
Made in Europe