fixSlash method

string fixSlash([
  1. bool? backSlash
])

Reverses slash in the String, by providing backSlash.

Also check fixPath getter. It does the same thing but backSlash is auto set according to current platform.

  • if backSlash is true it will replace all / with \\.
  • if backSlash is false it will replace all \\ with /.
  • if backSlash is null it will replace all slashes into the most common one.
  • All duplicated slashes will be replaced with a single slash.

Example

String foo1 = 'C:/Documents/user/test';
String revFoo1 = foo1.fixSlash(true); // returns 'C:\Documents\user\test'

String foo2 = 'C:\\Documents\\user\\test';
String revFoo2 = foo1.fixSlash(false); // returns 'C:/Documents/user/test'

String foo3 = 'C:/Documents\\user/test';
String revFoo3 = foo1.fixSlash(); // returns 'C:/Documents/user/test'

String foo4 = 'C:/Documents\\user\\test';
String revFoo4 = foo1.fixSlash(null); // returns 'C:\\Documents\\user\\test'

Implementation

string fixSlash([bool? backSlash]) {
  if (isBlank) {
    return blankIfNull;
  }
  var path = trim();
  bool hasFirstSlash = path.startsWith('/') || path.startsWith('\\');
  bool hasLastSlash = path.endsWith('/') || path.endsWith('\\');
  backSlash ??= count('\\') > count('/');
  if (backSlash) {
    path = (hasFirstSlash ? "\\" : "") + splitAny(['/', '\\'], true).join('\\');
    path = (hasLastSlash ? "$path\\" : path);
  } else {
    path = (hasFirstSlash ? "/" : "") + splitAny(['/', '\\'], true).join('/');
    path = (hasLastSlash ? "$path/" : path);
  }
  return path;
}