Minh Dan Minh Dan - 1 month ago 9
Javascript Question

How to convert path in javascript? especially with angularjs?

I have convert path




or from




Should i have to make function from scratch?
I want to use powerful lib of javascript and angularjs.
And how to do it?
Anything will be help me!


The first case just requires a slice:

if (str[0] === '.') {
  str = str.slice(1);

The second case, I'd probably use a RegEx with replace:

str.replace(/\\/g, '/'); // the 'g' is for global; without it, only the first occurrence is replaced

These are both vanilla JavaScript methods. No need for any fancy Angular tricks here.

These two methods can be put into a simple function like so:

function formatPathString (str) {
  if (str[0] === '.') str = str.slice(1);
  return str.replace(/\\/g, '/');

One caveat: in a normal JS string, backslashes are used to escape/form special characters, so a path with backslashes may prove problematic if the backslashes are not accurately escaped.

In other words "this\is\a\test".replace(/\\/g, '/') will not result in "this/is/a/test", but rather "thisisa\test" because the \t combination is meaningful, but the others aren't. You need to make sure any incoming strings with backslashes are properly escaped, as in: "this\\is\\a\\test" so that the replace method works as expected.