Now.js Framework Documentation

Now.js Framework Documentation

Utils

EN 15 Dec 2025 06:47

Utils

Overview

Utils is a collection of utility functions in Now.js Framework. It includes helper functions for string, number, date, object, array, and validation.

When to use:

  • Need to format strings, numbers, dates
  • Need to manipulate objects and arrays
  • Need to validate inputs
  • Need DOM utilities
  • Need common helper functions

Why use it:

  • ✅ Comprehensive utility functions
  • ✅ Consistent formatting
  • ✅ Thai locale support (Buddhist Era)
  • ✅ Type-safe operations
  • ✅ Well-tested functions

String Utilities

Utils.string.random(length)

Generate random string

const id = Utils.string.random(12);
// 'a3f7c9b2d5e8'

Utils.string.escape(unsafe)

Escape HTML characters

const safe = Utils.string.escape('<script>alert("xss")</script>');
// '&lt;script&gt;alert("xss")&lt;/script&gt;'

Utils.string.capitalize(str)

Capitalize first letter

Utils.string.capitalize('hello world');
// 'Hello world'

Utils.string.truncate(str, length, ending)

Truncate string

Utils.string.truncate('This is a long text', 10);
// 'This is a...'

Utils.string.truncate('This is a long text', 10, ' [more]');
// 'This is a [more]'

Utils.string.slugify(str)

Convert to URL-safe slug

Utils.string.slugify('Hello World! Test');
// 'hello-world-test'

Utils.string.stripTags(html)

Remove HTML tags

Utils.string.stripTags('<p>Hello <strong>World</strong></p>');
// 'Hello World'

Utils.string.sanitizeFilename(filename)

Sanitize filename

Utils.string.sanitizeFilename('file<>name?.jpg');
// 'filename.jpg'

Number Utilities

Utils.number.format(num, decimals)

Format number with thousand separators

Utils.number.format(1234567.89, 2);
// '1,234,567.89'

Utils.number.currency(amount, currency, locale)

Format as currency

Utils.number.currency(1500, 'THB', 'th-TH');
// '฿1,500.00'

Utils.number.currency(1500, 'USD');
// '$1,500.00'

Utils.number.percentage(num, decimals)

Format as percentage

Utils.number.percentage(0.75, 1);
// '75.0%'

Utils.number.fileSize(bytes)

Convert bytes to human readable

Utils.number.fileSize(1536000);
// '1.46 MB'

Utils.number.round/ceil/floor/truncate

Precision rounding

Utils.number.round(3.14159, 2);   // 3.14
Utils.number.ceil(3.14159, 2);   // 3.15
Utils.number.floor(3.14159, 2);  // 3.14
Utils.number.truncate(3.14159, 2); // 3.14

Date Utilities

Utils.date.format(date, format, locale)

Format date with tokens

Token Description Example
YYYY 4-digit year 2024 / 2567 (BE)
YY 2-digit year 24 / 67 (BE)
MM Month with zero 01-12
M Month 1-12
DD Day with zero 01-31
D Day 1-31
HH Hours 24h 00-23
hh Hours 12h 01-12
mm Minutes 00-59
ss Seconds 00-59
A AM/PM AM, PM
const date = new Date('2024-01-15');

// With tokens
Utils.date.format(date, 'DD/MM/YYYY');
// '15/01/2024'

// Thai Buddhist Era
Utils.date.format(date, 'DD/MM/YYYY', 'th-TH');
// '15/01/2567'

// Full datetime
Utils.date.format(date, 'YYYY-MM-DD HH:mm:ss');
// '2024-01-15 10:30:00'

Utils.date.add(date, amount, unit)

Add to date

const tomorrow = Utils.date.add(new Date(), 1, 'day');
const nextWeek = Utils.date.add(new Date(), 1, 'week');
const nextMonth = Utils.date.add(new Date(), 1, 'month');

Utils.date.compare(date1, date2)

Compare dates

Utils.date.compare(date1, date2);
// -1 if date1 < date2
//  0 if date1 == date2
//  1 if date1 > date2

Utils.date.fromTimestamp/toTimestamp

Convert timestamps

const date = Utils.date.fromTimestamp(1705312800);
const timestamp = Utils.date.toTimestamp(new Date());

Utils.date.daysInMonth(year, month)

Get days in month

Utils.date.daysInMonth(2024, 2); // 29 (leap year)
Utils.date.daysInMonth(2023, 2); // 28

Utils.date.isLeapYear(year)

Check leap year

Utils.date.isLeapYear(2024); // true
Utils.date.isLeapYear(2023); // false

Object Utilities

Utils.object.deepClone(obj)

Deep clone object

const copy = Utils.object.deepClone(original);

Utils.object.merge(target, ...sources)

Deep merge objects

const merged = Utils.object.merge(
  { a: 1, b: { c: 2 } },
  { b: { d: 3 } },
  { e: 4 }
);
// { a: 1, b: { c: 2, d: 3 }, e: 4 }

Utils.object.get(obj, path, defaultValue)

Get nested value safely

const user = { profile: { name: 'John' } };

Utils.object.get(user, 'profile.name');  // 'John'
Utils.object.get(user, 'profile.email', 'N/A');  // 'N/A'

Utils.object.isObject(item)

Check if plain object

Utils.object.isObject({});        // true
Utils.object.isObject([]);        // false
Utils.object.isObject(null);      // false

Array Utilities

Utils.array.chunk(arr, size)

Split into chunks

Utils.array.chunk([1,2,3,4,5], 2);
// [[1,2], [3,4], [5]]

Utils.array.unique(arr, key)

Remove duplicates

Utils.array.unique([1, 2, 2, 3, 3, 3]);
// [1, 2, 3]

// By key
Utils.array.unique(users, 'id');

Utils.array.shuffle(arr)

Randomize order

Utils.array.shuffle([1, 2, 3, 4, 5]);
// [3, 1, 5, 2, 4]

Utils.array.groupBy(arr, key)

Group by property

const users = [
  { name: 'John', role: 'admin' },
  { name: 'Jane', role: 'user' },
  { name: 'Bob', role: 'admin' }
];

Utils.array.groupBy(users, 'role');
// {
//   admin: [{ name: 'John', role: 'admin' }, { name: 'Bob', role: 'admin' }],
//   user: [{ name: 'Jane', role: 'user' }]
// }

Utils.array.flatten(arr, depth)

Flatten nested arrays

Utils.array.flatten([[1,2], [3, [4,5]]], 1);
// [1, 2, 3, [4, 5]]

Utils.array.flatten([[1,2], [3, [4,5]]], 2);
// [1, 2, 3, 4, 5]

Utils.array.findBy(arr, key, value)

Find by key-value

Utils.array.findBy(users, 'id', 123);
// { id: 123, name: 'John' }

Validation Utilities

Utils.validate.email(email)

Validate email

Utils.validate.email('user@example.com'); // true
Utils.validate.email('invalid-email');    // false

Utils.validate.url(url)

Validate URL

Utils.validate.url('https://example.com'); // true
Utils.validate.url('not-a-url');           // false

Utils.validate.phone(phone)

Validate phone

Utils.validate.phone('0812345678');  // true
Utils.validate.phone('1234');        // false

DOM Utilities

Utils.dom.ready(callback)

Wait for DOM ready

Utils.dom.ready(() => {
  console.log('DOM is ready');
});

Utils.dom.create(tag, attributes, children)

Create element

const button = Utils.dom.create('button', {
  class: 'btn btn-primary',
  onclick: () => console.log('clicked')
}, 'Click me');

Utils.dom.findParent(element, selector)

Find parent matching selector

const form = Utils.dom.findParent(input, 'form');

Built-in Formatters

Use in data-text directive:

<span data-text="price | currency('THB')">0</span>
<span data-text="date | date('DD/MM/YYYY')">-</span>
<span data-text="percent | percent(1)">0</span>
<span data-text="name | uppercase">-</span>
Formatter Description Example
number(decimals) Format number number(2)
currency(code) Format currency currency('THB')
percent(decimals) Format percentage percent(1)
date(format) Format date date('DD/MM/YYYY')
time(format) Format time time('HH:mm')
lowercase Lowercase -
uppercase Uppercase -
capitalize Capitalize -
default(value) Default value default('N/A')

Real-World Examples

Format User Display

function formatUser(user) {
  return {
    displayName: Utils.string.capitalize(user.name),
    email: Utils.string.escape(user.email),
    avatar: user.avatar || '/images/default-avatar.png',
    memberSince: Utils.date.format(user.createdAt, 'D MMM YYYY', 'en-US')
  };
}

Paginate Results

function paginate(items, page, perPage) {
  const chunks = Utils.array.chunk(items, perPage);
  return {
    data: chunks[page - 1] || [],
    total: items.length,
    pages: chunks.length,
    current: page
  };
}