This module provides Base64 encoding, case conversion, dedentation, glob matching, SemVer range matching, slug generation, and UTF-8 byte measurement.
Installation#
npm install @rcompat/stringpnpm add @rcompat/stringyarn add @rcompat/stringbun add @rcompat/stringUsage#
Base64 encoding/decoding#
import string from "@rcompat/string";
// encode to Base64
const encoded = string.Base64.encode("Hello, World!");
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// decode from Base64
const decoded = string.Base64.decode(encoded);
console.log(decoded); // "Hello, World!"Convert to camelcase#
import string from "@rcompat/string";
// from kebab case
string.toCamelCase("hello-world"); // "helloWorld"
string.toCamelCase("my-component"); // "myComponent"
// from snake case
string.toCamelCase("hello_world"); // "helloWorld"
string.toCamelCase("user_profile"); // "userProfile"
// mixed
string.toCamelCase("my-user_name"); // "myUserName"Dedent multi-line strings#
import string from "@rcompat/string";
// as a template tag
const sql = string.dedent`
SELECT *
FROM users
WHERE active = true
`;
// "SELECT *\nFROM users\nWHERE active = true"
// with interpolation
const table = "users";
const query = string.dedent`
SELECT *
FROM ${table}
WHERE id = 1
`;Convert glob to RegExp#
import string from "@rcompat/string";
// simple wildcards
const pattern = string.glob("*.js");
pattern.test("app.js"); // true
pattern.test("app.ts"); // false
pattern.test("dir/app.js"); // false
// double wildcard (recursive)
const recursive = string.glob("**/*.js");
recursive.test("app.js"); // true
recursive.test("src/app.js"); // true
recursive.test("src/lib/app.js"); // true
// single character wildcard
const single = string.glob("file?.txt");
single.test("file1.txt"); // true
single.test("fileA.txt"); // true
single.test("file10.txt"); // falseMatch a SemVer range#
string.semver(version, range) tests a concrete semantic version against an
exact version or a range. It follows
Deno's SemVer range grammar,
including comparators, carets, tildes, partial versions, wildcards, hyphen
ranges, and ||. An empty range matches any stable version.
Build metadata does not affect matching. A prerelease matches only if a
satisfied comparator set includes a prerelease comparator with the same
major, minor, and patch. Malformed inputs return false.
import string from "@rcompat/string";
string.semver("1.4.2", "^1.2.0 || 2.0.x"); // true
string.semver("2.1.0", "^1.2.0 || 2.0.x"); // false
string.semver("1.2.3+ci.7", "1.2.3"); // true
string.semver("1.3.0-beta.2", ">=1.3.0-beta.1 <2"); // trueConvert to slug#
import string from "@rcompat/string";
string.toSlug("Hello World"); // "hello-world"
string.toSlug("café"); // "cafe"
string.toSlug("naïve"); // "naive"
string.toSlug("foo bar"); // "foo-bar"Capitalize first letter#
import string from "@rcompat/string";
string.upperfirst("hello"); // "Hello"
string.upperfirst("world"); // "World"
string.upperfirst("javaScript"); // "JavaScript"Get UTF-8 byte length#
import string from "@rcompat/string";
// ASCII (1 byte per character)
string.utf8.bytelength("hello"); // 5
// unicode (variable bytes)
string.utf8.bytelength("héllo"); // 6 (é = 2 bytes)
string.utf8.bytelength("日本語"); // 9 (3 bytes each)
string.utf8.bytelength("🎉"); // 4 (emoji = 4 bytes)Get UTF-8 size#
import string from "@rcompat/string";
string.utf8.size("hello"); // 5
string.utf8.size("héllo"); // 6
string.utf8.size("日本語"); // 9
string.utf8.size("🎉"); // 4Examples#
Generate component names#
import string from "@rcompat/string";
function toComponentName(filename) {
// "my-button.svelte" -> "MyButton"
const name = filename.replace(/\.\w+$/, "");
return string.upperfirst(string.toCamelCase(name));
}
toComponentName("my-button.svelte"); // "MyButton"
toComponentName("user_profile.vue"); // "UserProfile"Build SQL queries#
import string from "@rcompat/string";
function buildQuery(table, conditions) {
return string.dedent`
SELECT *
FROM ${table}
WHERE ${conditions.join(" AND ")}
ORDER BY created_at DESC
`;
}
const query = buildQuery("users", ["active = true", "role = 'admin'"]);File matching#
import string from "@rcompat/string";
function matchFiles(files, pattern) {
const regex = string.glob(pattern);
return files.filter((file) => regex.test(file));
}
const files = ["app.js", "app.ts", "src/utils.js", "src/lib/helper.js"];
matchFiles(files, "*.js"); // ["app.js"]
matchFiles(files, "**/*.js"); // ["app.js", "src/utils.js", "src/lib/helper.js"]
matchFiles(files, "src/**/*.js"); // ["src/utils.js", "src/lib/helper.js"]Validate content length#
import string from "@rcompat/string";
function validateContent(content, maxBytes = 1024) {
const bytes = string.utf8.bytelength(content);
if (bytes > maxBytes) {
throw new Error(`Content exceeds ${maxBytes} bytes (got ${bytes})`);
}
return content;
}
validateContent("Hello"); // OK
validateContent("日本語".repeat(500)); // Error: exceeds limitEncode data for URL#
import string from "@rcompat/string";
function encodeState(state) {
const json = JSON.stringify(state);
return string.Base64.encode(json);
}
function decodeState(encoded) {
const json = string.Base64.decode(encoded);
return JSON.parse(json);
}
const state = { page: 1, filter: "active" };
const encoded = encodeState(state); // "eyJwYWdlIjoxLCJmaWx0ZXIiOiJhY3RpdmUifQ=="
const decoded = decodeState(encoded); // { page: 1, filter: "active" }Cross-Runtime Compatibility#
| Runtime | Supported |
|---|---|
| Browser | ✓ |
| Node.js | ✓ |
| Deno | ✓ |
| Bun | ✓ |
No configuration required — just import and use.
License#
MIT
Contributing#
See CONTRIBUTING.md in the repository root.