0

I have an array of strings with the following format

const references = [
'["C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-0.png"',
'"C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-1.png"]'
]

And I need to convert them into the following format

C:\Users\user\OneDrive\Desktop\PDES\images\fjJImt7Ym3pKvDCGzxwYL\fjJImt7Ym3pKvDCGzxwYL-1.png

Effectively doing the following

  1. Replacing all forward double slashes with one
  2. Removing the quotation marks
  3. Replacing the one backslash with a forward slash
  4. Removing the square brackets (those come from a JSON.stringfy in a different process)

To do this I've come up with the solution below

for (const imageRef of references ) {
  let path = imageRef.split('"').join('').split('[').join('').split(']').join('').split('/').join("\\\\")
}

But the array could have more than 25 file references and I think the process could be better. Is there any way I can make this better? I did consider using .replaceAll() but I'm working in Electron and that throws an error. I also took inspiration from this question but that was in 2010 and I'm sure things have changed.

SRR
  • 1,608
  • 1
  • 21
  • 51

2 Answers2

1

I'd use the URL API

const url = new URL('"C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-0.png"'
.replace(/[\[\]\"]/g,""))
console.log(url)
console.log(url.pathname.slice(1).replace(/\//g,"\\"))

Here is a map, note the string representation in JS of \ is \\

const references = [
'["C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-0.png"',
'"C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-1.png"]'
]
const DOSPaths = references
  .map(path => new URL(
      path.replace(/[\[\]\"]/g,"")
    ).pathname.slice(1)
     .replace(/\//g,"\\")
  );

console.log(DOSPaths);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • This works! But I forgot add in the square brackets and quotation marks in the original `references` array. – SRR Jun 30 '20 at 15:04
1

It's better to use regex, like this?

var refs = [  '["C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-0.png"',
'"C:\\Users\\user\\OneDrive\\Desktop\\PDES\\images\\fjJImt7Ym3pKvDCGzxwYL/fjJImt7Ym3pKvDCGzxwYL-1.png"]'
]

for (var i of refs){
    console.log(
    i.replace( /\//g, "\\" )
     .replace( /\\/g, "\\" )
     .replace( /\[/g, '' )
     .replace( /\]/g, '' )
     .replace( /\"/g, '' )
    )
}
Kresimir Pendic
  • 3,597
  • 1
  • 21
  • 28
  • Apologies, I forgot add in the square brackets and quotation marks in the original `references` array – SRR Jun 30 '20 at 15:03