0

Why is this giving me this error?

<script>
    function loadImg() {
        var imageChosen = document.getElementById('imageChosen').value.replace("C:\fakepath\","");
        alert(imageChosen);
        document.getElementById('image').src = imageChosen;
    }
</script>

I expect the image with id "image" to show the chosen image.

2
  • 2
    The first argument to replace() should be /C:\\fakepath\\/ or "C:\\fakepath\\" Commented Jul 30, 2019 at 20:50
  • 3
    JS strings use `\` to escape special characters. Commented Jul 30, 2019 at 20:51

2 Answers 2

5

The value in your call to replace() is not escaped properly.
The value should instead be:
"C:\\fakepath\\",""

Read more about escaping strings here

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is due to the escape string character \ (backslash)

When using strings in Javascript we may escape some character in the string. For example a break line (\n) or even a "(double quotes) when declaring the string or even an backslash \ need a escape.

Examples:

x = "my \\" // Will output as the same as "my \"

z = "my \"quotes\" // Will output as 'my "quotes" '

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.