I came across this question because I was trying to fix system paths. While the accepted answer works for converting strings to URLs (since they're always '/'), it does not work for file system paths. Below is a more comprehensive answer which I think fits the implied question better.
const ESCAPE = '\\';
const WRONG_SEPARATOR_FILE_SYSTEM = path.sep === path.win32.sep ?
path.posix.sep :
path.win32.sep;
const RGX_WRONG_SEPARATOR_FILE_SYSTEM = new RegExp(ESCAPE + WRONG_SEPARATOR_FILE_SYSTEM, 'g');
const RGX_WRONG_SEPARATOR_URL = new RegExp(ESCAPE + path.win32.sep, 'g');
function strToPath(str) {
return str.replace(RGX_WRONG_SEPARATOR_FILE_SYSTEM, path.sep);
}
function strToUrl(str) {
return str.replace(RGX_WRONG_SEPARATOR_URL, '/')
}
// using urls
img.src = strToUrl(thisImagePath)
// using files
strToPath('/some/posix/path') // will be correct regardless of system
strToPath('\some\win\path') // will be correct regardless of system