platform/core/route/lib/string_util.dart

44 lines
1.2 KiB
Dart
Raw Normal View History

2017-10-09 13:39:14 +00:00
/// Helper functions to performantly transform strings, without `RegExp`.
2021-05-14 07:02:50 +00:00
library angel3_route.string_util;
2017-10-09 13:39:14 +00:00
/// Removes leading and trailing occurrences of a pattern from a string.
String stripStray(String haystack, String needle) {
int firstSlash;
if (haystack.startsWith(needle)) {
firstSlash = haystack.indexOf(needle);
if (firstSlash == -1) return haystack;
} else {
firstSlash = -1;
}
2019-11-28 17:40:32 +00:00
if (firstSlash == haystack.length - 1) {
2017-10-09 13:39:14 +00:00
return haystack.length == 1 ? '' : haystack.substring(0, firstSlash);
2019-11-28 17:40:32 +00:00
}
2017-10-09 13:39:14 +00:00
// Find last leading index of slash
2021-04-03 05:50:52 +00:00
for (var i = firstSlash + 1; i < haystack.length; i++) {
2017-10-09 13:39:14 +00:00
if (haystack[i] != needle) {
var sub = haystack.substring(i);
2018-08-20 19:34:00 +00:00
if (!sub.endsWith(needle)) return sub;
2017-10-09 13:39:14 +00:00
var lastSlash = sub.lastIndexOf(needle);
2021-04-03 05:50:52 +00:00
for (var j = lastSlash - 1; j >= 0; j--) {
2017-10-09 13:39:14 +00:00
if (sub[j] != needle) {
return sub.substring(0, j + 1);
}
}
return lastSlash == -1 ? sub : sub.substring(0, lastSlash);
}
}
return haystack.substring(0, firstSlash);
}
String stripStraySlashes(String str) => stripStray(str, '/');
String stripRegexStraySlashes(String str) => stripStray(str, '\\/');