0
# String Processing
1
2
String manipulation utilities including case conversion, formatting, shortening, and encoding/decoding operations for text processing in JavaScript/TypeScript applications.
3
4
## Capabilities
5
6
### Case Conversion
7
8
Functions for converting string case formats commonly used in programming.
9
10
```typescript { .api }
11
/**
12
* Converts string to camelCase format
13
* @param value - String to convert (supports kebab-case, snake_case, PascalCase)
14
*/
15
function stringCamelCase(value: string): string;
16
17
/**
18
* Converts string to PascalCase format
19
* @param value - String to convert
20
*/
21
function stringPascalCase(value: string): string;
22
23
/**
24
* Converts first character to lowercase
25
* @param value - String to modify
26
*/
27
function stringLowerFirst(value: string): string;
28
29
/**
30
* Converts first character to uppercase
31
* @param value - String to modify
32
*/
33
function stringUpperFirst(value: string): string;
34
```
35
36
### String Formatting
37
38
Utilities for formatting and shortening strings for display purposes.
39
40
```typescript { .api }
41
/**
42
* Shortens string with ellipsis for display
43
* @param value - String to shorten
44
* @param prefixLength - Number of characters to keep at start (default: 6)
45
* @param suffixLength - Number of characters to keep at end (default: 6)
46
*/
47
function stringShorten(value: string, prefixLength?: number, suffixLength?: number): string;
48
```
49
50
### String Encoding
51
52
Functions for converting strings to binary data formats.
53
54
```typescript { .api }
55
/**
56
* Converts UTF-8 string to hex string
57
* @param value - String to convert to hex
58
*/
59
function stringToHex(value: string): HexString;
60
61
/**
62
* Converts UTF-8 string to Uint8Array
63
* @param value - String to convert to bytes
64
*/
65
function stringToU8a(value: string): Uint8Array;
66
```
67
68
## Usage Examples
69
70
**Case Conversion:**
71
72
```typescript
73
import {
74
stringCamelCase, stringPascalCase,
75
stringLowerFirst, stringUpperFirst
76
} from "@polkadot/util";
77
78
// Convert various formats to camelCase
79
console.log(stringCamelCase("hello-world")); // "helloWorld"
80
console.log(stringCamelCase("hello_world")); // "helloWorld"
81
console.log(stringCamelCase("HelloWorld")); // "helloWorld"
82
console.log(stringCamelCase("hello world")); // "helloWorld"
83
84
// Convert to PascalCase
85
console.log(stringPascalCase("hello-world")); // "HelloWorld"
86
console.log(stringPascalCase("hello_world")); // "HelloWorld"
87
console.log(stringPascalCase("helloWorld")); // "HelloWorld"
88
89
// First character manipulation
90
console.log(stringLowerFirst("HelloWorld")); // "helloWorld"
91
console.log(stringUpperFirst("helloWorld")); // "HelloWorld"
92
console.log(stringUpperFirst("API_KEY")); // "API_KEY"
93
```
94
95
**API and Variable Name Conversion:**
96
97
```typescript
98
import { stringCamelCase, stringPascalCase } from "@polkadot/util";
99
100
// Converting API response fields
101
const apiResponse = {
102
"user-name": "john_doe",
103
"email-address": "john@example.com",
104
"account-status": "active"
105
};
106
107
// Convert to camelCase for JavaScript usage
108
const jsObject = Object.entries(apiResponse).reduce((acc, [key, value]) => {
109
acc[stringCamelCase(key)] = value;
110
return acc;
111
}, {} as Record<string, string>);
112
113
console.log(jsObject);
114
// {
115
// userName: "john_doe",
116
// emailAddress: "john@example.com",
117
// accountStatus: "active"
118
// }
119
120
// Convert database column names to class names
121
const tableNames = ['user_accounts', 'api_tokens', 'session_data'];
122
const classNames = tableNames.map(stringPascalCase);
123
console.log(classNames); // ['UserAccounts', 'ApiTokens', 'SessionData']
124
```
125
126
**String Shortening:**
127
128
```typescript
129
import { stringShorten } from "@polkadot/util";
130
131
// Shorten long identifiers
132
const longHash = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
133
const short = stringShorten(longHash);
134
console.log(short); // "0x1234...abcdef" (6 chars + 6 chars)
135
136
// Custom prefix/suffix lengths
137
const address = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";
138
const shortAddress = stringShorten(address, 8, 4);
139
console.log(shortAddress); // "5GrwvaEF...utQY"
140
141
// Shorten user names for display
142
const longUsername = "very_long_username_that_needs_shortening";
143
const displayName = stringShorten(longUsername, 10, 3);
144
console.log(displayName); // "very_long_...ing"
145
```
146
147
**Text Encoding:**
148
149
```typescript
150
import { stringToHex, stringToU8a } from "@polkadot/util";
151
152
// Convert text to hex for blockchain storage
153
const message = "Hello, Polkadot!";
154
const hexEncoded = stringToHex(message);
155
console.log(hexEncoded); // "0x48656c6c6f2c20506f6c6b61646f7421"
156
157
// Convert text to bytes for cryptographic operations
158
const bytes = stringToU8a(message);
159
console.log(bytes); // Uint8Array(16) [72, 101, 108, 108, 111, 44, 32, 80, ...]
160
161
// Encoding multilingual text
162
const multilingual = "こんにちは 🌍 Hello";
163
const multiBytes = stringToU8a(multilingual);
164
const multiHex = stringToHex(multilingual);
165
console.log(`Bytes length: ${multiBytes.length}`); // Longer due to UTF-8 encoding
166
console.log(`Hex: ${multiHex}`);
167
```
168
169
**Form Field Processing:**
170
171
```typescript
172
import { stringCamelCase, stringLowerFirst, stringUpperFirst } from "@polkadot/util";
173
174
// Process form field names
175
function processFormData(formData: Record<string, any>) {
176
return Object.entries(formData).reduce((processed, [key, value]) => {
177
// Convert field names to camelCase for consistent API
178
const normalizedKey = stringCamelCase(key);
179
180
// Process string values
181
if (typeof value === 'string') {
182
// Capitalize names and titles
183
if (normalizedKey.includes('name') || normalizedKey.includes('title')) {
184
processed[normalizedKey] = stringUpperFirst(value.toLowerCase());
185
} else {
186
processed[normalizedKey] = value;
187
}
188
} else {
189
processed[normalizedKey] = value;
190
}
191
192
return processed;
193
}, {} as Record<string, any>);
194
}
195
196
const rawForm = {
197
"first-name": "JOHN",
198
"last_name": "DOE",
199
"email-address": "john.doe@example.com",
200
"phone_number": "+1234567890"
201
};
202
203
const processed = processFormData(rawForm);
204
console.log(processed);
205
// {
206
// firstName: "John",
207
// lastName: "Doe",
208
// emailAddress: "john.doe@example.com",
209
// phoneNumber: "+1234567890"
210
// }
211
```
212
213
**URL and Path Processing:**
214
215
```typescript
216
import { stringCamelCase, stringShorten } from "@polkadot/util";
217
218
// Convert URL paths to JavaScript identifiers
219
function urlToIdentifier(url: string): string {
220
// Extract path segments and convert to camelCase
221
const path = url.replace(/^https?:\/\/[^\/]+/, ''); // Remove domain
222
const segments = path.split('/').filter(Boolean);
223
const identifier = segments.join('-');
224
return stringCamelCase(identifier);
225
}
226
227
console.log(urlToIdentifier('/api/user-accounts/123')); // "apiUserAccounts123"
228
console.log(urlToIdentifier('/admin/system-settings')); // "adminSystemSettings"
229
230
// Create display-friendly URLs
231
function createDisplayUrl(fullUrl: string): string {
232
if (fullUrl.length <= 50) return fullUrl;
233
234
try {
235
const url = new URL(fullUrl);
236
const domain = url.hostname;
237
const path = url.pathname;
238
239
if (path.length > 20) {
240
const shortPath = stringShorten(path, 10, 10);
241
return `${domain}${shortPath}`;
242
}
243
244
return stringShorten(fullUrl, 25, 15);
245
} catch {
246
return stringShorten(fullUrl, 25, 15);
247
}
248
}
249
```
250
251
## Types
252
253
```typescript { .api }
254
type HexString = `0x${string}`;
255
```