-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathexternal.js
85 lines (83 loc) · 2.32 KB
/
external.js
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
82
83
84
85
//正则matchAll
export function matchesAll(str, pattern, flatten) {
if (!pattern.global) {
pattern = new RegExp(pattern.source, "g" + (pattern.ignoreCase ? "i" : "") + (pattern.multiline ? "m" : ""));
}
var matches = [];
var match;
while ((match = pattern.exec(str)) !== null) {
matches.push(match);
}
return flatten ? matches.flat() : matches;
}
//文本扩展
export function stringUtils() {
Object.defineProperties(String.prototype, {
replaceX: {
value: function (regex, replacement) {
let matches = matchesAll(this, regex,true);
if (matches && matches.length > 1) {
const hasCaptureGroup = /\$\d/.test(replacement);
if (hasCaptureGroup) {
return this.replace(regex, (m) => m.replace(regex, replacement));
} else {
return this.replace(regex, (m, p1) => m.replace(p1, replacement));
}
}
return this.replace(regex, replacement);
},
configurable: true,
enumerable: false,
writable: true
},
parseX: {
get: function () {
try {
//console.log(typeof this);
return JSON.parse(this);
} catch (e) {
console.log(e);
return this.startsWith("[") ? [] : {};
}
},
configurable: true,
enumerable: false,
}
});
}
//正则裁切
export function cut(text, start, end, method, All) {
let result = "";
let c = (t, s, e) => {
let result = "";
let rs = [];
let results = [];
try {
let lr = new RegExp(String.raw`${s}`.toString());
let rr = new RegExp(String.raw`${e}`.toString());
const segments = t.split(lr);
if (segments.length < 2) return '';
let cutSegments = segments.slice(1).map(segment => {
let splitSegment = segment.split(rr);
//log(splitSegment)
return splitSegment.length < 2 ? undefined : splitSegment[0] + e;
}).filter(f => f);
//log(cutSegments.at(-1))
if (All) {
return `[${cutSegments.join(',')}]`;
} else {
return cutSegments[0];
}
} catch (e) {
console.error("Error cutting text:", e);
}
return result;
}
result = c(text, start, end);
stringUtils();
if (method && typeof method === "function") {
result = method(result);
}
//console.log(result);
return result
}