-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathstring-replacer.ts
More file actions
81 lines (67 loc) · 1.62 KB
/
string-replacer.ts
File metadata and controls
81 lines (67 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict'
import { Str } from './str'
export class StringReplacer {
/**
* Stores the Str instance.
*/
private readonly strings: Str
/**
* Stores the "search" value.
*/
private readonly searchValue: string | RegExp
/**
* Determine whether to replace all occurences.
*/
private shouldReplaceAll: boolean
/**
* Determine whether to replace the last occurence.
*/
private shouldReplaceLast: boolean
/**
* Create a new string replacer instance.
*/
constructor (Strings: Str, searchValue: string | RegExp) {
this.strings = Strings
this.searchValue = searchValue
this.shouldReplaceAll = false
this.shouldReplaceLast = false
}
/**
* Replace all occurences of the search value.
*
* @returns {this}
*/
all (): this {
this.shouldReplaceAll = true
return this
}
/**
* Replace the last occurence of the search value.
*
* @returns {this}
*/
last (): this {
this.shouldReplaceLast = true
return this
}
/**
* Replace the search value with the given `replaceValue`.
*
* @param replaceValue
*
* @returns {Str}
*/
with (replaceValue: string): Str
with (replaceValue: string): Str
with (replacer: (substring: string, ...args: any[]) => string): Str
with (replacer: any): Str {
switch (true) {
case this.shouldReplaceAll:
return this.strings.replaceAll(this.searchValue, replacer ?? '')
case this.shouldReplaceLast:
return this.strings.replaceLast(this.searchValue, replacer ?? '')
default:
return this.strings.replace(this.searchValue, replacer ?? '')
}
}
}