Jake Sellers
Jake Sellers

Reputation: 2439

Change the backslashes in a URI to forward-slashes with javascript

I'm writing an app that will let the user import pictures. I'm running windows, so the file path that is returned when the user selects a picture has backslashes, which is what I believe to be causing javascript to fail when I pass the path to my import method. I get the file path with a simple html file input and use a submit button with an onclick call to my javascript:

 <input type="file" id="photo-to-import" />
 <input type="button" value="Submit" onclick="console.log($('#photo-to-import').val().replace('/\\/g','/'))"/>

console.log is normally where the function call would go, I've changed it for debugging. If I hard code in a file path to a picture and go through and manually change the slashes, it imports the picture, for example, I'll copy/paste a path:

C:\Users\Name\Desktop\desktop app\images\imageName.png

into the function and change the slashes I end up with:

<input type="button" value="Submit" onclick="onPhotoURISuccess('C:/Users/Name/Desktop/desktop app/images/imageName.png')"/>

and this works great. I have tried

.replace('\\\\', '/')
.replace('\\', '/')
...

and always get the exact same output, the string is unchanged every time.

Upvotes: 2

Views: 2194

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208615

Change replace('/\\/g','/') to replace(/\\/g,'/'), with the quotes you will be attempting to replace literal matches of the string '/\\/g' instead of using a regular expression literal.

For example, 'foo /\\/g bar'.replace('/\\/g','/') will give you 'foo / bar', and 'C:\\Users\\Name\\Desktop\\desktop app\\images\\imageName.png'.replace(/\\/g,'/') will give you 'C:\Users\Name\Desktop\desktop app\images\imageName.png'.

Upvotes: 4

Related Questions