A versatile utility package providing a wide range of functions for various programming needs. This documentation covers the String-Utility section.
Install the package via npm:
npm install gm-utility
The String-Utility module provides powerful string manipulation functions. Below is a detailed list of available functions, along with examples.
// Using ES Module (import)
import { Utility } from 'gm-utility';
const StringUtil = Utility.string;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const StringUtil = Utility.string;
Generates random hex-string
const randomString = StringUtil.getRandomCharacters();
console.log(randomString); // Example: "a3f7c9"
Extracts a substring from a string using start index and length.
const result = StringUtil.getSubstring('hello', 3, 1);
console.log(result); // Output: "el"
Extracts the substring between two specified substrings within a string.
const result = StringUtil.getStringBetweenStrings('hello developer world', 'hello', 'world');
console.log(result); // Output: "developer"
Returns the last n
characters of a string.
const result = StringUtil.getLastNCharacters('hello', 2);
console.log(result); // Output: "lo"
Splits a string into multiple lines, with each line having a specified maximum length.
const lines = StringUtil.splitTextInLinesByLength('hello world', 3);
console.log(lines); // Output: ["hel", "lo ", "wor", "ld"]
Splits text into lines by breaking at word boundaries, ensuring each line respects a specified character limit.
const lines = StringUtil.splitWordsInLinesByMaxLineLength('hello world', 5);
console.log(lines); // Output: ["hello", "world"]
Capitalizes the first letter of each word in a string.
const result = StringUtil.capitalizeFirstLetter('hello-world');
console.log(result); // Output: "Hello-World"
Generates an abbreviation by taking the first character of each word.
const abbreviation = StringUtil.abbreviateString('La Alta Vita');
console.log(abbreviation); // Output: "LAV"
Splits a string into parts using a specified delimiter.
const parts = StringUtil.getCleanSplit('hello,world', ',');
console.log(parts); // Output: ["hello", "world"]
A powerful utility package to simplify handling URLs, encode/decode URI strings, manipulate query strings, and extract essential request metadata. Ideal for developers working with HTTP requests and URL manipulations.
// Using ES Module (import)
import { Utility } from 'gm-utility';
const UrlUtil = Utility.url;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const UrlUtil = Utility.url;
- Convert relative URLs to absolute URLs.
- Encode and decode strings in base64.
- Convert objects to query strings.
- Extract and reduce essential information from request objects.
- Determine if a request is a developer request.
Converts a relative URL to an absolute URL.
Example:
UrlUtil.makeAbsolute("/user/login", "https://dev-test.com");
// Output: "https://dev-test.com/user/login"
Encodes a URI string into a base64 format.
Example:
UrlUtil.encodeURI("www.test.com/dashboard");
// Output: "d3d3LnRlc3QuY29tL2Rhc2hib2FyZA=="
Decodes a base64 encoded string back to its original text.
Example:
UrlUtil.decodeURI("d3d3LnRlc3QuY29tL2Rhc2hib2FyZA==");
// Output: "www.test.com/dashboard"
Converts an object into a query string.
Example:
UrlUtil.convertObjectToQueryString({ Name: "John", ID: 1120, Age: 60 });
// Output: "?Name=John&ID=1120&Age=60&"
Extracts and reduces relevant information from a request object.
Example:
UrlUtil.getReducedRequest({
body: { name: "John Doe", age: 30 },
params: {},
query: { search: "term" },
headers: { "content-type": "application/json" },
method: "POST",
url: "/example?search=term",
path: "/example",
ip: "127.0.0.1"
});
// Output: Reduced request object
Determines if a request is a developer request.
Example:
UrlUtil.isDeveloperRequest({ "content-type": "application/json" }, 'POST', true);
// Output: false
A utility library for performing common operations on arrays, objects, and strings. It includes methods for transformations, aggregations, and mathematical operations to simplify your development.
// Using ES Module (import)
import { Utility } from 'gm-utility';
const DsUtil = Utility.ds;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const DsUtil = Utility.ds;
Converts an array of objects into a single object, keyed by a specific property.
Example:
const data = [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' }
];
const result = dsUtilInstance.transformArrayToObjectByKey(data, 'id');
console.log(result);
// Output: { '1': { id: '1', name: 'Alice' }, '2': { id: '2', name: 'Bob' } }
Generates an array of numbers within a range.
Example:
const range = dsUtilInstance.generateRange(10, 1, 2);
console.log(range);
// Output: [1, 3, 5, 7, 9]
Finds the intersection of two arrays.
Example:
const result = dsUtilInstance.findIntersection([1, 2, 3], [2, 3, 4]);
console.log(result);
// Output: [2, 3]
Extracts a subset of an object based on a set of keys.
Example:
const obj = { a: 1, b: 2, c: 3 };
const subset = dsUtilInstance.getObjectSubset(obj, ['a', 'c']);
console.log(subset);
// Output: { a: 1, c: 3 }
Finds an object in an array that matches all properties of the target object.
Example:
const data = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ];
const result = dsUtilInstance.findMatchingObjectInArray({ id: 2 }, data);
console.log(result);
// Output: { id: 2, name: 'Bob' }
Removes unwanted characters from a string.
Example:
const cleanStr = dsUtilInstance.removeUnknownCharacters('abc@#$123');
console.log(cleanStr);
// Output: 'abc123'
Rounds all numerical fields in an object to two decimal places.
Example:
const obj = { a: 1.2345, b: 2.5678 };
const result = dsUtilInstance.roundNumericalFields(obj);
console.log(result);
// Output: { a: 1.23, b: 2.57 }
getElemCountOfArray<T>(d: T[], type: 'object' | 'array'): Record<string, number> | { key: T, frequency: number }[]
Counts the frequency of elements in an array.
Example:
const arr = [1, 2, 2, 3];
const count = dsUtilInstance.getElemCountOfArray(arr, 'array');
console.log(count);
// Output: [ { key: 1, frequency: 1 }, { key: 2, frequency: 2 }, { key: 3, frequency: 1 } ]
Flattens a nested object into a single-level object.
Example:
const nested = { a: { b: { c: 1 } } };
const result = dsUtilInstance.flattenObject(nested);
console.log(result);
// Output: { '.a.b.c': 1 }
Splits an array into batches of a specified size.
Example:
const result = dsUtilInstance.createBatchFromArray([1, 2, 3, 4, 5], 2);
console.log(result);
// Output: [ [1, 2], [3, 4], [5] ]
Finds the closest checkpoint for a given value.
Example:
const checkpoints = [10, 20, 30];
const result = dsUtilInstance.convergeValueToCheckpoints(25, checkpoints);
console.log(result);
// Output: 30
Rounds a number to a specified number of decimal places.
Example:
const rounded = dsUtilInstance.roundoff(1.234567, 3);
console.log(rounded);
// Output: 1.235
A utility package for simplifying date and time operations using the moment
library. It provides a set of functions to manipulate and format dates and times easily in JavaScript and TypeScript projects.
// Using ES Module (import)
import { Utility } from 'gm-utility';
const datetimeUtil = Utility.datetime;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const datetimeUtil = Utility.datetime;
Parses the given input date and returns a Moment object or formatted string.
Example:
const formattedDate = datetimeUtilInstance.formatDate('2023-12-24');
console.log(formattedDate);// '2023-12-24'
Formats a given date into the specified format.
Example:
const diff = datetimeUtilInstance.dateDifferenceBetween('2023-12-24', '2023-12-31', 'days');
console.log(diff); // -7
Returns the current date and time as a Moment object.
Example:
const currentDate = datetimeUtilInstance.now();
console.log(currentDate.format('YYYY-MM-DD HH:mm:ss'));
Returns the current date and time as a Moment object.
Example:
const newDate = datetimeUtilInstance.addDaysToDate('2024-12-24', 5);
console.log(newDate.format('YYYY-MM-DD')); // Output: '2024-12-29'
isDateBetween(stDate: string | Moment, enDate: string | Moment, input: string | Moment): string | boolean
Checks if a given date is between two other dates.
Example:
const isBetween = datetimeUtilInstance.isDateBetween('2024-12-20', '2024-12-30', '2024-12-24');
console.log(isBetween); // Output: true
Returns the day of the week (0-6) for the given date.
Example:
const dow = datetimeUtilInstance.getDOW('2024-12-24');
console.log(dow); // Output: 2 (Tuesday)
dateDifferenceBetween(start: Moment | string, end: Moment | string, on: moment.unitOfTime.Diff = 'days'): number
Calculates the difference between two dates based on the specified unit of time (default is days).
Example:
const diffInDays = datetimeUtilInstance.dateDifferenceBetween('2024-12-24', '2024-12-20');
console.log(diffInDays); // Output: 4
Adds a specified delta (in seconds by default) to a given date and returns the result.
Example:
const newDate = datetimeUtilInstance.addDeltaToMoment(600, '2024-12-24', 'seconds');
console.log(newDate.format('YYYY-MM-DD HH:mm:ss')); // Output: '2024-12-24 00:10:00'
Returns the maximum (latest) of the two provided Moment objects.
Example:
const maxTime = datetimeUtilInstance.getMax('2024-12-24 12:00:00', '2024-12-24 10:00:00');
console.log(maxTime.format('YYYY-MM-DD HH:mm:ss')); // Output: '2024-12-24 12:00:00'
Returns the start of the day (midnight) for the given date.
Example:
const startOfDay = datetimeUtilInstance.startOfDay('2024-12-24');
console.log(startOfDay); // Output: '2024-12-24 00:00:00'
Returns the end of the day (23:59:59) for the given date.
Example:
const endOfDay = datetimeUtilInstance.endOfDay('2024-12-24');
console.log(endOfDay); // Output: '2024-12-24 23:59:59'
Contributions are welcome! Please follow the steps below:
- Fork the repository.
- Create a feature branch.
- Commit your changes.
- Open a pull request.
This package is licensed under the ISC License. See the LICENSE file for more details.
If you encounter any issues or have suggestions, feel free to create an issue in the repository or reach out.
Happy coding!