Issues (49)

src/string.utils.js (9 issues)

1
import {ascii} from './lib/ascii';
2
import {_pop} from './lib/array';
3
import {validString, validArrayString, validNumber, validCharLength} from './lib/validate';
4
import {toUpperCase} from './string.cases';
5
import {entitiesDecode, entitiesEncode} from './lib/entities';
6
7
/**
8
 * Checks whether a string.
9
 * @playground
10
 * var isString = require('strman').isString;
11
 * let title = "A Javascript string manipulation library.";
12
 * let result = isString(title);
13
 * @param {String} value - The String!.
14
 * @return {Boolean} - if 'value' isString, return true, else false.
15
 */
16
const isString = value =>
17
    Object.prototype.toString.call(value) === '[object String]';
18
19
export {isString};
20
21
/**
22
 * Remove all spaces on left and right.
23
 * @playground
24
 * var trim = require('strman').trim;
25
 * let title = "   strman   ";
26
 * let result = trim(title);
27
 * @params {String} value - String to remove spaces.
28
 * @params {String = ' '} char - if you need remove other char on boarders.
29
 * @return {String} - String without boarders spaces.
30
 */
31
const trim = (value, char = ' ') => leftTrim(rightTrim(value, char), char);
32
33
export {trim};
34
35
/**
36
 * Remove all spaces on left.
37
 * @playground
38
 * var leftTrim = require('strman').leftTrim;
39
 * let title = "   strman";
40
 * let result = leftTrim(title);
41
 * @param {String} value - The String!.
42
 * @params {String = ' '} char - if you need remove other char on left boarders.
43
 * @return {String} - String without left boarders spaces.
44
 */
45
const leftTrim = (value, char = ' ') => replace(value, `^${char}+`, '');
46
47
export {leftTrim};
48
49
/**
50
 * Remove all spaces on right.
51
 * @playground
52
 * var rightTrim = require('strman').rightTrim;
53
 * let title = "strman     ";
54
 * let result = rightTrim(title);
55
 * @param {String} value - The String!.
56
 * @params {String = ' '} char - if you need remove other char on right boarders.
57
 * @return {String} - String without right boarders spaces.
58
 */
59
const rightTrim = (value, char = ' ') => replace(value, `${char}+$`, '');
60
61
 export {rightTrim};
62
63
/**
64
 * Remove all spaces and replace for value.
65
 * @playground
66
 * var removeSpaces = require('strman').removeSpaces;
67
 * let title = "  s t r  m  a n     ";
68
 * let result = removeSpaces(title);
69
 * @param {String} value - The String!.
70
 * @param {String} replaced - Value to replace.
71
 * @return {String} - String without spaces.
72
 */
73
const removeSpaces = (value, replaced = '') => replace(value, '\\s+', replaced);
74
75
export {removeSpaces};
76
77
/**
78
 * Replace all ocurrences of 'search' value to 'newvalue'.
79
80
 * var replace = require('strman').replace;
81
 * let title = "superman";
82
 * let result = replace(title, 'upe', 't');
83
 * @param {String} value - The String!.
84
 * @param {String} search - String to search.
85
 * @param {String} newvalue - String to replace.
86
 * @param {Boolean = true} caseSensitive - if you use caseSensitive replace.
87
 * @param {Boolean = true} multiline - if you use multiline replace.
88
 * @return {String} - String replaced with 'newvalue'.
89
 */
90
const replace = (value, search = '', newvalue = '', caseSensitive = true, multiline = true) => {
91
    var flags = caseSensitive ? 'g' : 'gi';
92
93
    multiline ? flags + 'm' : flags;
94
95
    return value.replace(new RegExp(search, flags), newvalue);
96
97
};
98
99
export {replace};
100
101
/**
102
 * Remove all non valid characters. Example: change á => a or ẽ => e.
103
 * @playground
104
 * var transliterate = require('strman').transliterate;
105
 * let title = "strmáñ";
106
 * let result = transliterate(title);
107
 * @param {String} value - The String!.
108
 * @return {String} - String without non valid characters.
109
 */
110
const transliterate = (value) => {
111
    let result = value;
112
    for(let key in ascii){
113
        for(let char in ascii[key]){
114
            result = replace(result, ascii[key][char], key);
115
        }
116
    }
117
    return result;
118
};
119
120
export {transliterate};
121
122
/**
123
 * Append Strings on Value with spreaded arguments
124
 * @param {String} value Initial value
125
 * @param {String} appends Spreaded array with strings to append
126
 * @return {String} The concatenated string
127
 * @playground
128
 * var strman = require('strman')
129
 *
130
 * let title = 's'
131
 * strman.append(title, 'tr', 'm', 'an') // returns 'strman'
132
 */
133
const append = (value, ...appends) => {
134
135
    validString(value);
136
    validArrayString(appends);
137
138
    if(length(appends) === 0){
139
        return value;
140
    }
141
142
    return value + appends.join('');
143
};
144
145
export {append};
146
147
/**
148
 * Append Array of Strings on Value
149
 * @param {String} value String initial
150
 * @param {String[]} append Array with strings to append
151
 * @return {String} The concatenated string
152
 * @playground
153
 * var strman = require('strman')
154
 *
155
 * let s = 's'
156
 * strman.appendArray(s, ['tr', 'm', 'an']) // returns 'strman'
157
 */
158
const appendArray = (value, appends = []) => {
159
160
    validString(value);
161
    validArrayString(appends);
162
163
    if(length(appends) === 0){
164
        return value;
165
    }
166
167
    return value + appends.join('');
168
};
169
170
export {appendArray};
171
172
173
/**
174
 * Get the character at index
175
 * @param {String} value The input string
176
 * @param {Number} index The index for which to extract the character
177
 * @return {String} The character at position index
178
 * @playground
179
 * var strman = require('strman')
180
 *
181
 * let title = 'abc'
182
 * strman.at(title, 1) // returns 'b'
183
 */
184
const at = (value, index) => {
185
    validString(value);
186
    validNumber(index);
187
188
    return substr(value, index, 1);
189
};
190
191
export {at};
192
193
/**
194
 * Returns array with strings between [start] and [end]
195
 * @param {String} value Input string
196
 * @param {String} start The start string to look for
197
 * @param {String} end The end string to look for
198
 * @return {String[]} An array with all the matches between a pair of `start` and `end`
199
 * @playground
200
 * var strman = require('strman')
201
 *
202
 * let title = '[abc][def]'
203
 * strman.between(title, '[', ']') // returns ['abc', 'def']
204
 */
205
const between = (value, start, end) => {
206
207
    let result = null;
208
209
    validArrayString([value, start, end]);
210
211
    result = split(value, end);
212
213
    result = result.map((text) => {
214
        return substr(text, indexOf(text, start)+length(start));
215
    });
216
217
    result = _pop(result);
218
219
    return result;
220
};
221
222
export {between};
223
224
/**
225
 * Returns an array consisting of the characters in the string.
226
 * @param {String} value The input string
227
 * @returns {String[]} The array with the single characters of `value`
228
 * @playground
229
 * var strman = require('strman')
230
 *
231
 * let title = 'abc'
232
 * strman.chars(title) // returns ['a', 'b', 'c']
233
 */
234
const chars = value => {
235
    validString(value);
236
    return value.split('');
237
};
238
239
export {chars};
240
241
/**
242
 * Replaces consecutive whitespace characters with a single space
243
 * @param {String} value The input string
244
 * @return {String} The whitespace collapsed string
245
 * @playground
246
 * var strman = require('strman')
247
 *
248
 * let title = '  a  b  c  '
249
 * strman.collapseWhitespace(title) // returns 'a b c'
250
 */
251
const collapseWhitespace = (value) => trim(replace(value, '\\s\\s+',' '));
252
253
export {collapseWhitespace};
254
255
/**
256
 * Remove all non word characters.
257
 * @playground
258
 * var removeNonWords = require('strman').removeNonWords;
259
 * let title = "__strman../";
260
 * let result = removeNonWords(title);
261
 * @param {String} value - The String!.
262
 * @param {String} replaced - Value to replace.
263
 * @return {String} - String without non word characters.
264
 */
265
const removeNonWords = (value, replaced = '') => replace(value, '[^\\w]+', replaced);
266
267
export {removeNonWords};
268
269
/**
270
 * Verifies that the needle is contained in value
271
 * @param {String} value The input string
272
 * @param {String} needle The string which is checked to be contained within `value`
273
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching
274
 * @return {Boolean} True if `needle` is contained
275
 * @playground
276
 * var strman = require('strman')
277
 *
278
 * let title = 'Daniel Leite'
279
 * let needle = 'leite'
280
 * strman.contains(title, needle, false) // returns true
281
 */
282
const contains = (value, needle, caseSensitive = true) => {
283
284
    if(caseSensitive){
285
        return indexOf(value, needle) > -1;
286
    }
287
288
    return indexOf(toUpperCase(value), toUpperCase(needle)) > -1;
289
290
};
291
292
export {contains};
293
294
/**
295
 * Verifies that all needles are contained in value
296
 * @param {String} value The input string
297
 * @param {String[]} needles An array of strings which are checked to be contained within `value`
298
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching
299
 * @return {Boolean} True if all `needles` are contained
300
 * @playground
301
 * var strman = require('strman')
302
 *
303
 * let title = 'Daniel Leite'
304
 * let needles = ['Leite', 'Daniel']
305
 * strman.containsAll(title, needles) // returns true
306
 */
307
const containsAll = (value, needles, caseSensitive = true) => {
308
309
    if(length(needles) === 0){
310
        return false;
311
    }
312
313
    for(let i = 0; i < length(needles); i++){
314
        if(!contains(value, needles[i], caseSensitive)){
315
            return false;
316
        }
317
    }
318
    return true;
319
};
320
321
export {containsAll};
322
323
/**
324
 * Verifies that one or more of needles are contained in value
325
 * @param {String} value The input string
326
 * @param {String[]} needles An array of string which are checked to be contained within `value`
327
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching
328
 * @return {Boolean} True if at least one of `needles` is contained
329
 * @playground
330
 * var strman = require('strman')
331
 *
332
 * let title = 'Daniel Leite'
333
 * let needles = ['Leite', 'Oliveira']
334
 * strman.containsAny(title, needles) // returns true
335
 */
336
const containsAny = (value, needles, caseSensitive = true) => {
337
    for(let i = 0; i < length(needles); i++){
338
        if(contains(value, needles[i], caseSensitive)){
339
            return true;
340
        }
341
    }
342
    return false;
343
};
344
345
export {containsAny};
346
347
/**
348
 * Polyfill to countSubstr function
349
 * @private
350
 * @param value,
351
 * @param substr,
352
 * @param position = 0,
353
 * @param count = 0,
354
 * @param allowOverlapping = false
355
 * @return integer
356
 */
357
const _countSubstring = (value, _substr, allowOverlapping = false, position = 0, count = 0) => {
358
359
    let _position = indexOf(value, _substr, position);
360
361
    if(_position === -1){
362
        return count;
363
    }
364
365
    if(!allowOverlapping){
366
        _position = _position + length(_substr) - 1;
367
    }
368
369
    return _countSubstring(value, _substr, allowOverlapping, _position + 1, count + 1);
370
371
};
372
373
/**
374
 * Count the number of times substr appears in value
375
 * @param {String} value The input string
376
 * @param {String} substr The substring to look for
377
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching
378
 * @param {Boolean} [allowOverlapping=false] Allow overlapping substrings to be counted
379
 * @return {Number} The number of matches
380
 * @playground
381
 * var strman = require('strman')
382
 *
383
 * let title = 'Daniel Leite'
384
 * let substr = 'Leite'
385
 * strman.counSubstr(title, substr) // returns 1
386
 */
387
const countSubstr = (value, _substr, caseSensitive = true, allowOverlapping = false) => {
388
389
    if(!caseSensitive){
390
        value = toUpperCase(value);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter value. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
391
        _substr = toUpperCase(_substr);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter _substr. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
392
    }
393
394
    return _countSubstring(value, _substr, allowOverlapping);
395
396
};
397
398
export {countSubstr};
399
400
/**
401
 * Test if `value` ends with `search`
402
 * @param {String} value The input string
403
 * @param {String} search The string to search for
404
 * @param {?Number} [position] The start position/index within `value` to start searching
405
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching
406
 * @return {Boolean} True if `input` ends with `search`
407
 * @playground
408
 * var strman = require('strman')
409
 *
410
 * let value = 'Daniel Leite'
411
 * let search = 'Leite'
412
 * strman.endsWith(value, search) // returns true
413
 */
414
const endsWith = (value, search, position = null, caseSensitive = true) => {
415
416
    let lastIndex = null;
417
418
    if (typeof position !== 'number' || !isFinite(position)
419
            || Math.floor(position) !== position || position > length(value)) {
420
        position = length(value);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter position. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
421
    }
422
423
    position -= length(search);
424
425
    if(caseSensitive){
426
        lastIndex = indexOf(value, search, position);
427
    }else{
428
        lastIndex = indexOf(toUpperCase(value), toUpperCase(search), position);
429
    }
430
431
    return lastIndex !== -1 && lastIndex === position;
432
433
};
434
435
export {endsWith};
436
437
/**
438
 * Test if 'value' starts with 'search'
439
 * @playground
440
 * var startsWith = require('strman').startsWith;
441
 * let title = "strman";
442
 * let result = startsWith(title, 'str');
443
 * @param {String} value - The String!.
444
 * @param {String} search - Value to search.
445
 * @param {Number = 0} position - offset to search.
446
 * @param {Boolean = true} caseSensitive - if you use caseSensitive to test.
447
 * @return {Boolean} - If 'value' startsWith 'search' return true, else false.
448
 */
449
const startsWith = (value, search, position = 0, caseSensitive = true) => {
450
451
    if(caseSensitive){
452
        return substr(value, position, length(search)) === search;
453
    }
454
455
    return substr(toUpperCase(value), position, length(search)) === toUpperCase(search);
456
457
};
458
459
export {startsWith};
460
461
/**
462
 * Ensures that the `value` begins with `substr`. If it doesn't, it's prepended.
463
 * @param {String} value The input string
464
 * @param {String} substr The substr to be ensured to be left
465
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching for determining if `value` already starts with `substr`
466
 * @return {String} The string which is guarenteed to start with `substr`
467
 * @playground
468
 * var strman = require('strman')
469
 *
470
 * let value = 'Leite'
471
 * let substr = 'Daniel '
472
 * strman.ensureLeft(value, substr) // returns 'Daniel Leite'
473
 */
474
const ensureLeft = (value, _substr, caseSensitive = true)  => {
475
    if(!startsWith(value, _substr, 0, caseSensitive)){
476
        return append(_substr, value);
477
    }
478
479
    return value;
480
};
481
482
export  {ensureLeft};
483
484
/**
485
 * Ensures that the [value] ends with [substr]. If it doesn't, it's appended.
486
 * @param {String} value The input string
487
 * @param {String} substr The substr to be ensured to be right
488
 * @param {Boolean} [caseSensitive=true] Use case (in-)sensitive matching for determining if `value` already ends with `substr`
489
 * @return {String} The string which is guarenteed to start with `substr`
490
 * @playground
491
 * var strman = require('strman')
492
 *
493
 * let value = 'Daniel'
494
 * let substr = ' Leite'
495
 * strman.ensureRight(value, substr) // returns 'Daniel Leite'
496
 */
497
const ensureRight = (value, _substr, caseSensitive = true)  => {
498
499
    if(!endsWith(value, _substr, null, caseSensitive)){
500
        return append(value, _substr);
501
    }
502
503
    return value;
504
};
505
506
export {ensureRight};
507
508
 /**
509
 * Return the first 'n' chars of string.
510
 * @playground
511
 * var first = require('strman').first;
512
 * let title = "strman";
513
 * let result = first(title, 3);
514
 * @param {String} value - The String!.
515
 * @param {String} n - Number of chars to return.
516
 * @return {String} - Return 'n' firsts chars.
517
 */
518
const first = (value, n) => substr(value, 0, n);
519
520
export {first};
521
522
/**
523
 * Return the last 'n' chars of string.
524
 * @playground
525
 * var last = require('strman').last;
526
 * let title = "strman";
527
 * let result = last(title, 3);
528
 * @param {String} value - The String!.
529
 * @param {String} n - Number of chars to return.
530
 * @return {String} - Return 'n' lasts chars.
531
 */
532
const last = (value, n) => substr(value, -1 * n, n);
533
534
export {last};
535
536
/**
537
 * The indexOf() method returns the index within the calling String of the first occurrence
538
 * of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
539
 * @playground
540
 * var indexOf = require('strman').indexOf;
541
 * let title = "strman";
542
 * let result = indexOf(title, 'man');
543
 * @param {String} value - The String!.
544
 * @param {String} needle - Value to search.
545
 * @param {Number = 0} offset - Offset to search.
546
 * @param {Boolean = true} caseSensitive - if you use caseSensitive to test.
547
 * @return {Number} - Return position of the first occurrence of 'needle'.
548
 */
549
const indexOf = (value, needle, offset = 0, caseSensitive = true) => {
550
    if(caseSensitive){
551
        return value.indexOf(needle, offset);
552
    }
553
554
    return toUpperCase(value).indexOf(toUpperCase(needle), offset);
555
};
556
557
export {indexOf};
558
559
/**
560
 * The lastIndexOf() method returns the index within the calling String object of the last
561
 * occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the
562
 * value is not found.
563
 * @playground
564
 * var lastIndexOf = require('strman').lastIndexOf;
565
 * let title = "strman strman";
566
 * let result = lastIndexOf(title, 'str');
567
 * @param {String} value - The String!.
568
 * @param {String} needle - Value to search.
569
 * @param {Number = undefined} offset - Offset to search.
570
 * @param {Boolean = true} caseSensitive - if you use caseSensitive to test.
571
 * @return {Number} - Return position of the last occurrence of 'needle'.
572
 */
573
const lastIndexOf = (value, needle, offset = undefined, caseSensitive = true) => {
574
    if(caseSensitive){
575
        return value.lastIndexOf(needle, offset);
576
    }
577
    return toUpperCase(value).lastIndexOf(toUpperCase(needle), offset);
578
};
579
580
export {lastIndexOf};
581
582
/**
583
 * Inserts 'substr' into the 'value' at the 'index' provided.
584
 * @playground
585
 * var insert = require('strman').insert;
586
 * let title = "trman";
587
 * let result = insert(title, 's', 0);
588
 * @param {String} value - The String!.
589
 * @param {String} _substr - Value to insert.
590
 * @param {Number} index - Index to insert substr.
591
 * @return {String} - String with substr added.
592
 */
593
const insert = (value, _substr, index) => {
594
595
    let start = null;
596
    let end = null;
597
598
    if(index > length(value)){
599
        return value;
600
    }
601
602
    start = substr(value, 0, index);
603
    end = substr(value, index, length(value));
604
605
    return append(start, _substr, end);
606
607
};
608
609
export {insert};
610
611
/**
612
 * Returns the length of the string.
613
 * @playground
614
 * var length = require('strman').length;
615
 * let title = "strman";
616
 * let result = length(title);
617
 * @param {String} value - The String!.
618
 * @return {Number} - Length of the string..
619
 */
620
const length = value => {
621
    let i = 0;
622
    while(value[i] !== undefined){
623
        i++;
624
    }
625
    return i;
626
};
627
628
export {length};
629
630
/**
631
 * Returns a new string of a given length such that the beginning of the string is padded.
632
 * @playground
633
 * var leftPad = require('strman').leftPad;
634
 * let title = "strman";
635
 * let result = leftPad(title, 10, 0);
636
 * @param {String} value - The String!.
637
 * @param {Number} _length - Max length of String.
638
 * @param {Char} char - Char to repeat.
639
 * @return {String} - String pad.
640
 */
641
 const leftPad = (value, _length, char = ' ') => {
642
643
    let result = value;
644
    char = String(char);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter char. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
645
646
    if(length(char) > 1){
647
        char = substr(char, 0, 1);
648
    }
649
650
    validCharLength(char);
651
652
    _length = _length - length(value);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter _length. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
653
654
    result = append(repeat(char, _length), result);
655
656
    return result;
657
};
658
659
export {leftPad};
660
661
/**
662
 * Returns a new string of a given length such that the ending of the string is padded.
663
 * @playground
664
 * var rightPad = require('strman').rightPad;
665
 * let title = "strman";
666
 * let result = rightPad(title, 10, 0);
667
 * @param {String} value - The String!.
668
 * @param {Number} _length - Max length of String.
669
 * @param {Char} char - Char to repeat.
670
 * @return {String} - String pad.
671
 */
672
const rightPad = (value, _length, char = ' ') => {
673
674
    let result = value;
675
    char = String(char);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter char. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
676
677
    if(length(char) > 1){
678
        char = substr(char, 0, 1);
679
    }
680
681
    validCharLength(char);
682
683
    _length = _length - length(value);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter _length. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
684
685
    result = append(result, repeat(char, _length));
686
687
    return result;
688
};
689
690
export {rightPad};
691
692
/**
693
 * Alias to substr function.
694
 * @playground
695
 * var substr = require('strman').substr;
696
 * let title = "strman";
697
 * let result = substr(title, 0, 3);
698
 * @param {String} value - The String!.
699
 * @param {Number} start - Substring starts.
700
 * @param {Number} _length - Substring length.
701
 * @return {String} - The Substring!
702
 */
703
const substr = (value, start, _length = undefined) => value.substr(start, _length);
704
705
export {substr};
706
707
/**
708
 * Alias to split function.
709
 * @playground
710
 * var split = require('strman').split;
711
 * let title = "strman";
712
 * let result = split(title, '');
713
 * @param {String} value - The String!.
714
 * @param {String} separator - Split separator.
715
 * @param {Number = undefined} limit - Split limit.
716
 * @return {String} - The String splited!
717
 */
718
const split = (value, separator, limit = undefined) => value.split(separator, limit);
719
720
export {split};
721
722
 /**
723
 * Returns a new string starting with 'prepends'.
724
 * @playground
725
 * var prepend = require('strman').prepend;
726
 * let title = "strman";
727
 * let result = prepend(title, '_');
728
 * @param {String} value - The String!.
729
 * @param {...String} prepends - Strings to prepend.
730
 * @return {String} - The String prepended!
731
 */
732
const prepend = (value, ...prepends) => {
733
734
    validString(value);
735
    validArrayString(prepends);
736
737
    if(length(prepends) === 0){
738
        return value;
739
    }
740
741
    return prepends.join('') + value;
742
};
743
744
export {prepend};
745
746
 /**
747
 * Returns a new string starting with 'prepends'.
748
 * @playground
749
 * var prependArray = require('strman').prependArray;
750
 * let title = "strman";
751
 * let result = prependArray(title, '_');
752
 * @param {String} value - The String!.
753
 * @param {String[]} prepends - Strings to prepend.
754
 * @return {String} - The String prepended!
755
 */
756
const prependArray = (value, prepends = []) => {
757
758
    validString(value);
759
    validArrayString(prepends);
760
761
    if(length(prepends) === 0){
762
        return value;
763
    }
764
765
    return prepends.join('') + value;
766
};
767
768
export {prependArray};
769
770
 /**
771
 * Returns a new string with the 'prefix' removed, if present.
772
 * @playground
773
 * var removeLeft = require('strman').removeLeft;
774
 * let title = "strman";
775
 * let result = removeLeft(title, 'str');
776
 * @param {String} value - The String!.
777
 * @param {String} prefix - String to remove on left.
778
 * @param {Boolean = true} caseSensitive - If you need to caseSensitive.
779
 * @return {String} - The String without prefix!
780
 */
781
const removeLeft = (value, prefix, caseSensitive = true) => {
782
783
    if(startsWith(value, prefix, 0, caseSensitive)){
784
        return substr(value, length(prefix));
785
    }
786
787
    return value;
788
};
789
790
export {removeLeft};
791
792
/**
793
 * Returns a new string with the 'suffix' removed, if present.
794
 * @playground
795
 * var removeRight = require('strman').removeRight;
796
 * let title = "strman";
797
 * let result = removeRight(title, 'man');
798
 * @param {String} value - The String!.
799
 * @param {String} suffix - String to remove on right.
800
 * @param {Boolean = true} caseSensitive - If you need to caseSensitive.
801
 * @return {String} - The String without suffix!
802
 */
803
const removeRight = (value, suffix, caseSensitive = true) => {
804
    let _length = length(value) - length(suffix);
805
806
    if(endsWith(value, suffix, null, caseSensitive)){
807
        return substr(value, 0, _length);
808
    }
809
810
    return value;
811
};
812
813
export {removeRight};
814
815
/**
816
 * Returns a repeated string given a multiplier.
817
 * @playground
818
 * var repeat = require('strman').repeat;
819
 * let title = "strman";
820
 * let result = repeat(title, 5);
821
 * @param {String} value - The String!.
822
 * @param {Number} multiplier - Number of repeats.
823
 * @return {String} - The String repeated!
824
 */
825
const repeat = (value, multiplier) => {
826
    let i = 0;
827
    let result = '';
828
    while(multiplier > i++) {
829
        result += value;
830
    }
831
    return result;
832
};
833
834
export {repeat};
835
836
/**
837
 * Returns a reversed string.
838
 * @playground
839
 * var reverse = require('strman').reverse;
840
 * let title = "strman";
841
 * let result = reverse(title);
842
 * @param {String} value - The String!.
843
 * @return {String} - The String reversed!
844
 */
845
const reverse = (value) => {
846
    let i = 0;
847
    let reversed = '';
848
    while(length(value) > i++){
849
        reversed = append(reversed, substr(value, -1*i, 1));
850
    }
851
    return reversed;
852
};
853
854
export {reverse};
855
856
/**
857
 * It returns a array with its values in random order.
858
 * @private
859
 * @param {Array} value - The array!.
860
 * @return {Array} - The Array shuffled!
861
*/
862
const _shuffle =(array) => {
863
    let j;
864
    let x;
865
    let i;
866
    for (i = length(array); i; i -= 1) {
867
        j = Math.floor(Math.random() * i);
868
        x = array[i - 1];
869
        array[i - 1] = array[j];
870
        array[j] = x;
871
    }
872
    return array;
873
};
874
875
/**
876
 * It returns a string with its characters in random order.
877
 * @playground
878
 * var shuffle = require('strman').shuffle;
879
 * let title = "strman";
880
 * let result = shuffle(title);
881
 * @param {String} value - The String!.
882
 * @return {String} - The String shuffled!
883
 */
884
const shuffle = (value) => _shuffle(split(value)).join('');
885
886
export {shuffle};
887
888
 /**
889
 * Surrounds a 'value' with the given 'substr'.
890
 * @playground
891
 * var surround = require('strman').surround;
892
 * let title = "strman";
893
 * let result = surround(title, '<', '>');
894
 * @param {String} value - The String!.
895
 * @param {String = ''} _substr - The substr to append on left, if substrRight is null, this is appended in right.
896
 * @param {String = null} _substrRight - The substr to append on right.
897
 * @return {String} - The String with surround substrs!
898
 */
899
const surround = (value, _substr = '', _substrRight = null) =>
900
    append(_substr, value, _substrRight === null ? _substr : _substrRight);
901
902
export {surround};
903
904
/**
905
 * Alias to slice method.
906
 * @playground
907
 * var slice = require('strman').slice;
908
 * let title = "strman";
909
 * let result = slice(title, 2, 5);
910
 * @param {String} value - The String!.
911
 * @param {Number} beginSlice - Start of slice.
912
 * @param {Number} endSlice - End of slice.
913
 * @return {String} - The String sliced!
914
 */
915
 const slice = (value, beginSlice, endSlice = undefined) => value.slice(beginSlice, endSlice);
916
917
 export {slice};
918
919
/**
920
 * Truncate the string securely, not cutting a word in half. It always returns the last full word.
921
 * @playground
922
 * var safeTruncate = require('strman').safeTruncate;
923
 * let title = "A Javascript string manipulation library.";
924
 * let result = safeTruncate(title, 15, '...');
925
 * @param {String} value - Value will be truncated securely.
926
 * @param {Number} _length - Max size of the returned string.
927
 * @param {String} [_append = ''] - Value that will be added to the end of the return string. Example: '...'
928
 * @returns {String} - String truncated safely.
929
 */
930
const safeTruncate = (value, _length, _append = '') => {
931
932
    let truncated = '';
933
934
    if(_length === 0){
935
        return '';
936
    }
937
938
    if (_length >= length(value)) {
939
        return value;
940
    }
941
942
    _length -= length(_append) ;
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter _length. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
943
    truncated = substr(value, 0, _length);
944
945
    let position = indexOf(value, ' ', _length - 1);
946
947
    if(position !== _length){
948
        let lastPos = lastIndexOf(truncated, ' ');
949
        truncated = substr(truncated, 0, lastPos);
950
    }
951
952
    return append(truncated, _append);
953
954
};
955
956
export {safeTruncate};
957
958
/**
959
 * Truncate the unsecured form string, cutting the independent string of required position.
960
 * @playground
961
 * var truncate = require('strman').truncate;
962
 * let title = "A Javascript string manipulation library.";
963
 * let result = truncate(title, 16, '...');
964
 * @param {String} value - Value will be truncated unsecurely.
965
 * @param {Number} _length - Size of the returned string.
966
 * @param {String} [_append = ''] - Value that will be added to the end of the return string. Example: '...'
967
 * @returns {String} - String truncated unsafely.
968
 */
969
const truncate = (value, _length, _append = '') => {
970
971
    let truncated = '';
972
973
    if(_length === 0){
974
        return '';
975
    }
976
977
    if (_length >= length(value)) {
978
        return value;
979
    }
980
981
    _length -= length(_append) ;
0 ignored issues
show
Comprehensibility Best Practice introduced by
This re-assigns to the parameter _length. Re-assigning to parameters often makes code less readable, consider introducing a new variable instead.
Loading history...
982
    truncated = substr(value, 0, _length);
983
984
    return append(truncated, _append);
985
986
};
987
988
export {truncate};
989
990
991
/**
992
 * Remove empty strings from strings array.
993
 * @playground
994
 * var removeEmptyStrings = require('strman').removeEmptyStrings;
995
 * let titles = ["A Javascript string manipulation library.", null, undefined, '', ' '];
996
 * let result = removeEmptyStrings(titles);
997
 * @param {String[]} strings - Array of strings that will be cleaned.
998
 * @returns {String[]} - Array of strings without empty strings.
999
 */
1000
const removeEmptyStrings = (strings) => strings.filter(string => string && string !== '');
1001
1002
export {removeEmptyStrings};
1003
1004
/**
1005
 * Formats a string using parameters.
1006
 * @playground
1007
 * var format = require('strman').format;
1008
 * let select = "SELECT * FROM CONTACTS WHERE NAME LIKE '%{0}%' AND EMAIL LIKE '%{1}%'";
1009
 * let result = format(select, "DANIEL", "GMAIL");
1010
 * @param {String} value - Value that will be formatted.
1011
 * @param {String[]} params - Array with the parameters described in the string.
1012
 * @returns {String} - Formatted string.
1013
 */
1014
const format = (value, params = []) =>
1015
    replace(value, '{(\\w+)}',
1016
        (match, index) => typeof params[index] !== undefined ? params[index] : match
1017
    );
1018
1019
export {format};
1020
1021
/**
1022
 * Compares two strings to each other. If they are equivalent, a zero is returned. Otherwise,
1023
 * most of these routines will return a positive or negative result corresponding to whether stringA
1024
 * is lexicographically greater than, or less than, respectively, than stringB.
1025
 * @playground
1026
 * var compare = require('strman').compare;
1027
 * let result = compare("foo", "bar");
1028
 * @param {String} stringA - String for the comparative
1029
 * @param {String} stringB - String to be compared
1030
 * @returns {Number} - +1 if [stringA] > [stringB], -1 if [stringA] < [stringB] and 0 if [stringA] = [stringB]
1031
 */
1032
const compare = (stringA, stringB) => {
1033
    if(equal(stringA, stringB)){
1034
        return 0;
1035
    }
1036
1037
    return stringA > stringB? 1 : -1;
1038
};
1039
1040
export {compare};
1041
1042
/**
1043
 * Tests if two strings are equal.
1044
 * @playground
1045
 * var equal = require('strman').equal;
1046
 * let result = equal("foo", "foo");
1047
 * @param {String} stringA - String for the comparative
1048
 * @param {String} stringB - String to be compared
1049
 * @returns {Boolean} - [stringA] is equal [stringB]
1050
 */
1051
const equal = (stringA, stringB) => stringA === stringB;
1052
1053
export {equal};
1054
1055
/**
1056
 * Tests if two strings are inequal.
1057
 * @playground
1058
 * var inequal = require('strman').inequal;
1059
 * let result = inequal("foo", "foo");
1060
 * @param {String} stringA - String for the comparative
1061
 * @param {String} stringB - String to be compared
1062
 * @returns {Boolean} - [stringA] is inequal [stringB]
1063
 */
1064
const inequal = (stringA, stringB) => stringA !== stringB;
1065
1066
export {inequal};
1067
1068
/**
1069
 * Convert string chars to hexadecimal unicode (4 digits)
1070
 * @playground
1071
 * var hexEncode = require('strman').hexEncode;
1072
 * let result = hexEncode("strman");
1073
 * @param {String} value - Value to encode
1074
 * @returns {String} - String in hexadecimal format.
1075
 */
1076
const hexEncode = (value) =>
1077
    chars(value).map((data) => leftPad(data.charCodeAt(0).toString(16), 4, '0')).join('');
1078
1079
export {hexEncode};
1080
1081
/**
1082
 * Convert hexadecimal unicode (4 digits) string to string chars
1083
 * @playground
1084
 * var hexDecode = require('strman').hexDecode;
1085
 * let result = hexDecode("007300740072006d0061006e");
1086
 * @param {String} value - Value to decode
1087
 * @returns {String} - String decoded.
1088
 */
1089
const hexDecode = (value) =>
1090
    value.match(/.{1,4}/g).map((data)=>String.fromCharCode(parseInt(data, 16))).join('');
1091
1092
export {hexDecode};
1093
1094
/**
1095
 * Convert string chars to binary unicode (16 digits)
1096
 * @playground
1097
 * var binEncode = require('strman').binEncode;
1098
 * let result = binEncode("strman");
1099
 * @param {String} value - Value to encode
1100
 * @returns {String} - String in binary format.
1101
 */
1102
const binEncode = (value) =>
1103
    chars(value).map((data) => leftPad(data.charCodeAt(0).toString(2), 16, '0')).join('');
1104
1105
export {binEncode};
1106
/**
1107
 * Convert binary unicode (16 digits) string to string chars
1108
 * @playground
1109
 * var binDecode = require('strman').binDecode;
1110
 * let result = binDecode("000000000111001100000000011101000000000001110010000000000110110100000000011000010000000001101110");
1111
 * @param {String} value - Value to decode
1112
 * @returns {String} - String decoded.
1113
 */
1114
const binDecode = (value) =>
1115
    value.match(/.{1,16}/g).map((data)=>String.fromCharCode(parseInt(data, 2))).join('');
1116
1117
export {binDecode};
1118
1119
/**
1120
 * Convert string chars to decimal unicode (5 digits)
1121
 * @playground
1122
 * var decEncode = require('strman').decEncode;
1123
 * let result = decEncode("strman");
1124
 * @param {String} value - Value to encode
1125
 * @returns {String} - String in decimal format.
1126
 */
1127
const decEncode = (value) =>
1128
    chars(value).map((data) => leftPad(data.charCodeAt(0).toString(10), 5, '0')).join('');
1129
1130
export {decEncode};
1131
1132
/**
1133
 * Convert binary unicode (16 digits) string to string chars
1134
 * @playground
1135
 * var decDecode = require('strman').decDecode;
1136
 * let result = decDecode("001150011600114001090009700110");
1137
 * @param {String} value - Value to decode
1138
 * @returns {String} - String decoded.
1139
 */
1140
const decDecode = (value) =>
1141
    value.match(/.{1,5}/g).map((data)=>String.fromCharCode(parseInt(data, 10))).join('');
1142
1143
export {decDecode};
1144
1145
/**
1146
 * Replaces all characters with the appropriate UTF-8 escape sequences.
1147
 * @playground
1148
 * var urlEncode = require('strman').urlEncode;
1149
 * let result = urlEncode("https://github.com/dleitee/strman/&name=áéíóú");
1150
 * @param {String} value - The string to be encoded
1151
 * @returns {String} - Returns a string in which all non-alphanumeric characters except -_.
1152
 */
1153
const urlEncode = (value) => encodeURI(value);
1154
1155
export {urlEncode};
1156
1157
/**
1158
 * Decodes URL-encoded string
1159
 * @playground
1160
 * var urlDecode = require('strman').urlDecode;
1161
 * let result = urlDecode("https://github.com/dleitee/strman/&name=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA");
1162
 * @param {String} value - The string to be decoded
1163
 * @returns {String} - Returns the decoded string.
1164
 */
1165
const urlDecode = (value) => decodeURI(value);
1166
1167
export {urlDecode};
1168
1169
/**
1170
 * Encodes data with MIME base64.
1171
 * Base64-encoded data takes about 33% more space than the original data.
1172
 * @playground
1173
 * var base64Encode = require('strman').base64Encode;
1174
 * let result = base64Encode("strman");
1175
 * @param {String} value - The data to encode.
1176
 * @returns - The encoded data.
1177
 */
1178
const base64Encode = (value) => new Buffer(value).toString('base64');
1179
1180
export {base64Encode};
1181
1182
/**
1183
 * Decodes data encoded with MIME base64
1184
 * @playground
1185
 * var base64Decode = require('strman').base64Decode;
1186
 * let result = base64Decode("c3RybWFu");
1187
 * @param {String} value - The data to decode.
1188
 * @returns - The decoded data.
1189
 */
1190
const base64Decode = (value) => new Buffer(value, 'base64').toString();
1191
1192
export {base64Decode};
1193
1194
/**
1195
 * Convert all HTML entities to applicable characters.
1196
 * @playground
1197
 * var htmlDecode = require('strman').htmlDecode;
1198
 * let result = htmlDecode('&lt;div&gt;');
1199
 * @params {String} value - value to decode.
1200
 * @returns - The decoded data.
1201
 */
1202
const htmlDecode = (value) =>
1203
    replace(value, '(&\\w+;)',
1204
        (match, index) =>
1205
            typeof entitiesDecode[index] !== undefined ? entitiesDecode[index] : match
1206
        );
1207
1208
export {htmlDecode};
1209
1210
/**
1211
 * Convert all applicable characters to HTML entities.
1212
 * @playground
1213
 * var htmlEncode = require('strman').htmlEncode;
1214
 * let result = htmlEncode('<div>');
1215
 * @params {String} value - value to encode.
1216
 * @returns - The encoded data.
1217
 */
1218
const htmlEncode = (value) => replace(value, '[\\u00A0-\\u9999<>\\&]',
1219
    (match) =>
1220
        typeof entitiesEncode[match] !== undefined ? entitiesEncode[match] : match
1221
    , true, true);
1222
1223
export {htmlEncode};
1224