String
Methods that jComponent adds to String.prototype for formatting, parsing, validating and converting text.
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.
str.arg(obj, [encode], [def])| Parameter | Type | Description |
|---|---|---|
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:
| 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. |
'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"
'/search?q={q}'.arg({ q: 'a b&c' }, true); // "/search?q=a%20b%26c"
'<b>{name}</b>'.arg({ name: '<i>' }, 'escape'); // "<b><i></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.
str.COMPILABLE()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.
'<div data-bind="user.name"></div>'.COMPILABLE(); // true
'<div>Hello</div>'.COMPILABLE(); // false
method
str.encode()
Encodes the characters <, >, & and " as HTML entities.
str.encode()Returns String The encoded text.
'<a href="#">Tom & Ann</a>'.encode(); // "<a href="#">Tom & Ann</a>"
method
str.env()
Replaces [key] with a value from ENV() and [.path] with a value from the model.
str.env()Returns String The text with the values applied.
A key without a value stays in the text.
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.
str.flags([path], [value], [type])| Parameter | Type | Description |
|---|---|---|
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.
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.
str.format(a, [b], [c], ...)| Parameter | Type | Description |
|---|---|---|
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.
'{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.
str.isEmail()Returns Boolean true for a valid 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.
str.isJSONDate()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.
'2026-11-18T10:20:30.000Z'.isJSONDate(); // true
'2026-11-18'.isJSONDate(); // false
method
str.isPhone()
Checks whether the text is a phone number.
str.isPhone()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 ..
'+421903123456'.isPhone(); // true
'123-456-7890'.isPhone(); // true
'12345'.isPhone(); // false
method
str.isURL()
Checks whether the text is an http or https address.
str.isURL()Returns Boolean true for a valid 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.
str.padLeft(length, [char])| Parameter | Type | Description |
|---|---|---|
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.
'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.
str.padRight(length, [char])| Parameter | Type | Description |
|---|---|---|
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.
'5'.padRight(3, '-'); // "5--"
method
str.parseConfig([def], [callback])
Parses a key:value;key:value text into an object.
str.parseConfig([def], [callback])| Parameter | Type | Description |
|---|---|---|
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.
'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}
'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.
str.parseDate([format])| Parameter | Type | Description |
|---|---|---|
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.
'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
'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.
str.parseEncoded()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.
'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.
str.parseExpire()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 |
'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.
str.parseFloat([def])| Parameter | Type | Description |
|---|---|---|
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.
'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.
str.parseInt([def])| Parameter | Type | Description |
|---|---|---|
def? |
Number |
The value returned when the text has no number. Default: 0 |
Returns Number The parsed 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.
str.parseSource([type])| Parameter | Type | Description |
|---|---|---|
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.
'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.
str.removeTags()Returns String The text without tags.
Everything from a < to the next > is treated as a tag.
'<p>Hello <b>world</b></p>'.removeTags(); // "Hello world"
method
str.render(model, [repository])
Compiles the text as a Tangular template and renders it.
str.render(model, [repository])| Parameter | Type | Description |
|---|---|---|
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.
'Hello {{ name }}'.render({ name: '<Ann>' }); // "Hello <Ann>"
'{{ $.title }}: {{ name }}'.render({ name: 'Ann' }, { title: 'User' }); // "User: Ann"
method
str.ROOT([nobase])
Prepends DEF.root or DEF.baseurl to a relative URL.
str.ROOT([nobase])| Parameter | Type | Description |
|---|---|---|
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.
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.
str.SCOPE(element)| Parameter | Type | Description |
|---|---|---|
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.
<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.
str.slug([max])| Parameter | Type | Description |
|---|---|---|
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.
'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.
str.toASCII()Returns String The converted text.
The conversion covers the characters á ä č ď é ě í ï ĺ ľ ň ó ô ö ő ŕ ř š ť ú ů ü ű ý ÿ ž ć in both cases. Other characters stay unchanged.
'Žluťoučký kůň'.toASCII(); // "Zlutoucky kun"
'Señor'.toASCII(); // "Señor"
method
str.toSearch()
Normalizes the text for fuzzy searching.
str.toSearch()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.
'Ž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.
str.VARIABLES([args])| Parameter | Type | Description |
|---|---|---|
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.
'--color=red--Color: --color--'.VARIABLES(); // "Color: red"
'Size: --size--'.VARIABLES({ size: '10px' }); // "Size: 10px"
'Size: --size--'.VARIABLES(); // "Size: --size--"