Skip to content

Commit c154352

Browse files
author
Sven Ulrich
committed
updatedeps: moved class in its own file
1 parent eaefd59 commit c154352

File tree

6 files changed

+297
-285
lines changed

6 files changed

+297
-285
lines changed

$string.ts

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
import { EOL } from 'os';
2+
3+
export class $String extends String {
4+
private static readonly regexNumber = /{(\d+(:\w*)?)}/g;
5+
private static readonly regexObject = /{(\w+(:\w*)?)}/g;
6+
7+
public static empty = '';
8+
9+
public static isNullOrWhiteSpace(value: string | null | undefined): boolean {
10+
try {
11+
if (value == null || value == 'undefined') {
12+
return true;
13+
}
14+
15+
return value.toString().replace(/\s/g, '').length < 1;
16+
}
17+
catch (e) {
18+
console.log(e);
19+
return false;
20+
}
21+
}
22+
23+
public static join(delimiter: string, ...args: (string | object | Array<any>)[]): string {
24+
try {
25+
const firstArg = args[0];
26+
if (Array.isArray(firstArg) || firstArg instanceof Array) {
27+
let tempString = $String.empty;
28+
29+
for (let i = 0; i < firstArg.length; i++) {
30+
const current = firstArg[i];
31+
if (i < firstArg.length - 1) {
32+
tempString += current + delimiter;
33+
}
34+
else {
35+
tempString += current;
36+
}
37+
}
38+
39+
return tempString;
40+
}
41+
else if (typeof firstArg === 'object') {
42+
let tempString = $String.empty;
43+
const objectArg = firstArg;
44+
const keys = Object.keys(firstArg); //get all Properties of the Object as Array
45+
keys.forEach(element => { tempString += (<any>objectArg)[element] + delimiter; });
46+
tempString = tempString.slice(0, tempString.length - delimiter.length); //remove last delimiter
47+
return tempString;
48+
}
49+
50+
const stringArray = <string[]>args;
51+
52+
return $String.joinString(delimiter, ...stringArray);
53+
}
54+
catch (e) {
55+
console.log(e);
56+
return $String.empty;
57+
}
58+
}
59+
60+
public static format(format: string, ...args: any[]): string {
61+
try {
62+
if (format.match($String.regexNumber)) {
63+
return $String.formatString($String.regexNumber, format, args);
64+
}
65+
66+
if (format.match($String.regexObject)) {
67+
return $String.formatString($String.regexObject, format, args, true);
68+
}
69+
70+
return format;
71+
}
72+
catch (e) {
73+
console.log(e);
74+
return $String.empty;
75+
}
76+
}
77+
78+
private static formatString(regex: any, format: string, args: any, parseByObject = false): string {
79+
return format.replace(regex, function (match, x) { //0
80+
const s = match.split(':');
81+
if (s.length > 1) {
82+
x = s[0].replace('{', '');
83+
match = s[1].replace('}', ''); //U
84+
}
85+
86+
let arg;
87+
if (parseByObject) {
88+
arg = args[0][x];
89+
}
90+
else {
91+
arg = args[x];
92+
}
93+
94+
if (arg == null || arg == undefined || match.match(/{\d+}/)) {
95+
return arg;
96+
}
97+
98+
arg = $String.parsePattern(match, arg);
99+
return typeof arg != 'undefined' && arg != null ? arg : $String.empty;
100+
});
101+
}
102+
103+
private static parsePattern(match: 'L' | 'U' | 'd' | 's' | 'n' | 'x' | 'X' | string, arg: string | Date | number | any): string {
104+
switch (match) {
105+
case 'L': {
106+
arg = arg.toLocaleLowerCase();
107+
return arg;
108+
}
109+
case 'U': {
110+
arg = arg.toLocaleUpperCase();
111+
return arg;
112+
}
113+
case 'd': {
114+
if (typeof (arg) === 'string') {
115+
return $String.getDisplayDateFromString(arg);
116+
}
117+
else if (arg instanceof Date) {
118+
return $String.format('{0:00}.{1:00}.{2:0000}', arg.getDate(), arg.getMonth(), arg.getFullYear());
119+
}
120+
break;
121+
}
122+
case 's': {
123+
if (typeof (arg) === 'string') {
124+
return $String.getSortableDateFromString(arg);
125+
}
126+
else if (arg instanceof Date) {
127+
return $String.format('{0:0000}-{1:00}-{2:00}', arg.getFullYear(), arg.getMonth(), arg.getDate());
128+
}
129+
break;
130+
}
131+
case 'n': {//Tausender Trennzeichen
132+
if (typeof (arg) !== 'string')
133+
arg = arg.toString();
134+
const replacedString = arg.replace(/,/g, '.');
135+
if (isNaN(parseFloat(replacedString)) || replacedString.length <= 3) {
136+
break;
137+
}
138+
139+
const numberparts = replacedString.split(/\D+/g);
140+
let parts = numberparts;
141+
142+
if (numberparts.length > 1) {
143+
parts = [$String.joinString('', ...(numberparts.splice(0, numberparts.length - 1))), numberparts[numberparts.length - 1]];
144+
}
145+
146+
const integer = parts[0];
147+
148+
const mod = integer.length % 3;
149+
let output = (mod > 0 ? (integer.substring(0, mod)) : $String.empty);
150+
151+
const remainingGroups = integer.substring(mod).match(/.{3}/g);
152+
output = output + '.' + $String.join('.', remainingGroups);
153+
arg = output + (parts.length > 1 ? ',' + parts[1] : '');
154+
return arg;
155+
}
156+
case 'x': {
157+
return this.decimalToHexString(arg);
158+
}
159+
case 'X': {
160+
return this.decimalToHexString(arg, true);
161+
}
162+
default: {
163+
break;
164+
}
165+
}
166+
167+
if ((typeof (arg) === 'number' || !isNaN(arg)) && !isNaN(+match) && !$String.isNullOrWhiteSpace(arg)) {
168+
return $String.formatNumber(arg, match);
169+
}
170+
171+
return arg;
172+
}
173+
174+
private static decimalToHexString(value: string, upperCase = false) {
175+
const parsed = parseFloat(value);
176+
const hexNumber = parsed.toString(16);
177+
return upperCase ? hexNumber.toLocaleUpperCase() : hexNumber;
178+
}
179+
180+
private static getDisplayDateFromString(input: string): string {
181+
const splitted: string[] = input.split('-');
182+
183+
if (splitted.length <= 1) {
184+
return input;
185+
}
186+
187+
let day = splitted[splitted.length - 1];
188+
const month = splitted[splitted.length - 2];
189+
const year = splitted[splitted.length - 3];
190+
day = day.split('T')[0];
191+
day = day.split(' ')[0];
192+
193+
return `${day}.${month}.${year}`;
194+
}
195+
196+
private static getSortableDateFromString(input: string): string {
197+
const splitted = input.replace(',', '').split('.');
198+
if (splitted.length <= 1) {
199+
return input;
200+
}
201+
202+
const times = splitted[splitted.length - 1].split(' ');
203+
let time = $String.empty;
204+
if (times.length > 1) {
205+
time = times[times.length - 1];
206+
}
207+
208+
const year = splitted[splitted.length - 1].split(' ')[0];
209+
const month = splitted[splitted.length - 2];
210+
const day = splitted[splitted.length - 3];
211+
let result = `${year}-${month}-${day}`;
212+
213+
if (!$String.isNullOrWhiteSpace(time) && time.length > 1) {
214+
result += `T${time}`;
215+
}
216+
else {
217+
result += 'T00:00:00';
218+
}
219+
220+
return result;
221+
}
222+
223+
private static formatNumber(input: number, formatTemplate: string): string {
224+
const count = formatTemplate.length;
225+
const stringValue = input.toString();
226+
if (count <= stringValue.length) {
227+
return stringValue;
228+
}
229+
230+
let remainingCount = count - stringValue.length;
231+
remainingCount += 1; //Array must have an extra entry
232+
233+
return new Array(remainingCount).join('0') + stringValue;
234+
}
235+
236+
private static joinString(delimiter: string, ...args: string[]): string {
237+
let temp = $String.empty;
238+
for (let i = 0; i < args.length; i++) {
239+
if ((typeof args[i] == 'string' && $String.isNullOrWhiteSpace(args[i]))
240+
|| (typeof args[i] != 'number' && typeof args[i] != 'string')) {
241+
continue;
242+
}
243+
244+
const arg = '' + args[i];
245+
temp += arg;
246+
for (let i2 = i + 1; i2 < args.length; i2++) {
247+
if ($String.isNullOrWhiteSpace(args[i2])) {
248+
continue;
249+
}
250+
251+
temp += delimiter;
252+
i = i2 - 1;
253+
break;
254+
}
255+
}
256+
257+
return temp;
258+
}
259+
}

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,5 @@
1414
- feature: !IMPORTANT methods/properties starting with uppercase are marked deprecated now and will be removed with version 2.0.0! Check the deprecated infos
1515
- feature: added class `$String` for everybody who is facing issues when `String` is used.
1616
- feature: `String.isNullOrWhiteSpace` accepts null or undefined now
17-
- chore: Updated packages
17+
- chore: Updated packages
18+
- chore: added linting

readme.md renamed to README.md

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,64 @@
11

2+
[![CircleCI](https://circleci.com/gh/sevensc/typescript-string-operations.svg?style=shield)](https://app.circleci.com/pipelines/github/sevensc/typescript-string-operations)
3+
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=sevensc_typescript-string-operations&metric=alert_status)](https://sonarcloud.io/dashboard?id=sevensc_typescript-string-operations)
4+
![npm](https://img.shields.io/npm/v/typescript-string-operations)
5+
![npm](https://img.shields.io/npm/dw/typescript-string-operations)
6+
27

3-
![CircleCI](https://img.shields.io/circleci/build/github/iwt-svenulrich/typescript-string-operations?logo=circleci&token=9234d9f6803b37ebfcd4887fa2d6d51aa2cf5214)
4-
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=sevensc_typescript-string-operations&metric=alert_status)](https://sonarcloud.io/dashboard?id=sevensc_typescript-string-operations)![npm](https://img.shields.io/npm/v/typescript-string-operations)![npm](https://img.shields.io/npm/dw/typescript-string-operations)
58
# Simple lightweight string operation library for Typescript.
69
## No jQuery required! Unit tested, works with Angular.
710

811
```typescript
912
import { String, StringBuilder } from 'typescript-string-operations';
1013
```
1114

15+
I recently got feedback that sometimes there are issues when using `String`, since its actually replacing the native `String` object from JavaScript. Youcan use `$String` instead.
16+
17+
```typescript
18+
import { $String } from 'typescript-string-operations';
19+
```
20+
1221
#### USAGE:
1322

14-
### String.Empty
23+
### String.empty
1524
```typescript
16-
var id = String.Empty;
25+
var id = String.empty;
1726
```
1827

19-
### String.IsNullOrWhiteSpace():
28+
### String.isNullOrWhiteSpace():
2029
```typescript
2130
var id = image.GetId();
22-
if(String.IsNullOrWhiteSpace(id))
31+
if(String.isNullOrWhiteSpace(id))
2332
return image;
2433
```
25-
### String.Format():
34+
### String.format():
2635

2736
```typescript
2837
var id = image.GetId()
29-
String.Format("image_{0}.jpg", id)
38+
String.format("image_{0}.jpg", id)
3039
output: "image_2db5da20-1c5d-4f1a-8fd4-b41e34c8c5b5.jpg";
3140
```
3241

3342
Specifier available!
3443
```typescript
35-
var value = String.Format("{0:L}", "APPLE"); //output "apple"
44+
var value = String.format("{0:L}", "APPLE"); //output "apple"
3645

37-
value = String.Format("{0:U}", "apple"); // output "APPLE"
46+
value = String.format("{0:U}", "apple"); // output "APPLE"
3847

39-
value = String.Format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"
48+
value = String.format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"
4049

4150

42-
value = String.Format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"
51+
value = String.format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"
4352

44-
value = String.Format("{0:n}", 1000000);
53+
value = String.format("{0:n}", 1000000);
4554
//output "1.000.000"
4655

47-
value = String.Format("{0:00}", 1);
56+
value = String.format("{0:00}", 1);
4857
//output "01"
4958
```
5059

5160
## UPDATE
52-
#### String Format for Objects including specifiers
61+
#### String.format for Objects including specifiers
5362

5463
```typescript
5564
var fruit = new Fruit();
@@ -58,7 +67,7 @@ fruit.color = "RED";
5867
fruit.shippingDate = new Date(2018, 1, 1);
5968
fruit.amount = 10000;
6069

61-
String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
70+
String.format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
6271
// output: the APPLE is red shipped on 2018-01-01 with an amount of 10.000
6372

6473
```
@@ -78,30 +87,30 @@ String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amo
7887
### String.Join():
7988

8089
```typescript
81-
var value = String.Join("; ", "Apple", "Banana");
90+
var value = String.join("; ", "Apple", "Banana");
8291
//output: "Apple; Banana";
8392
```
8493
#### OR
8594

8695
```typescript
8796
let object = { Name: "Foo", Value: "Bar" };
88-
var value = String.Join('.', object);
97+
var value = String.join('.', object);
8998
//output: "Foo.Bar";
9099

91100
var array = ['Apple', 'Banana']
92-
var value = String.Join("; ", array);
101+
var value = String.join("; ", array);
93102
//output: "Apple; Banana";
94103
```
95104

96105
## Methods
97106

98107
| Method | Type | Description | Parameter |
99108
| :------------------------:|:-----------:|:--------------------------:|:----------:|
100-
| `Empty` | `Property` | simply returns `""`. |
101-
| `IsNullOrWhiteSpace` | `Method` | returns true value if given parameter is either null, empty or undefined. | `format`, `args`
102-
| `Format` | `Method` | Converts the value of objects to strings based on the formats specified and inserts them into another string. | `format`, `args`
103-
| `Join` | `Method` | Combines arguments delimited by given seperator.| `delimiter`,`args`
104-
| `Join` | `Method` | Combines arguments delimited by given seperator from array. | `delimiter`,`array` |
109+
| `empty` | `Property` | simply returns `""`. |
110+
| `isNullOrWhiteSpace` | `Method` | returns true value if given parameter is either null, empty or undefined. | `format`, `args`
111+
| `format` | `Method` | Converts the value of objects to strings based on the formats specified and inserts them into another string. | `format`, `args`
112+
| `join` | `Method` | Combines arguments delimited by given seperator.| `delimiter`,`args`
113+
| `join` | `Method` | Combines arguments delimited by given seperator from array. | `delimiter`,`array` |
105114

106115

107116
### StringBuilder

0 commit comments

Comments
 (0)