7

I have a JavaScript variable that I echo out using PHP which is shown like this in the page source:

var db_1 = 'C:\this\path';

When I set the value of a text field with that variable like so:

$('#myinput').val(db_1);

The slashes have disappeared and only the other characters are left!

Why is this and how can I put the slashes back in??

Thanks all

0

3 Answers 3

11

A backslash is an escape character in JS. They are lost when the string literal is parsed.

You can't put them back, because you have no way of telling where they were. You have to make sure they remain in the string in the first place (by representing them with an escape sequence).

var db_1 = 'C:\\this\\path';
Sign up to request clarification or add additional context in comments.

5 Comments

I have tried using replace '\' with '\\' but that didn't work.
If by "replace" you mean "replace in the source code" then it should work (and does for me). If you mean "Use the JavaScript String replace method" then of course it won't work — I refer you back to the second sentence of my answer. There are no backslash characters in the string, just escape sequences. Since there are no backslash characters, you won't get any changes if you try to replace them with something else.
Ah I see, I'll do a str_replace with PHP then. Thanks!
@Abs: It needs to be output as \\ originally, you can't fix it after the fact. What you actually have there otherwise is c: followed by a tab character (\t is a tab in Javascript) followed by hispath (because \p is not special, so the backslash is ignored). So what PHP outputs has to look like var db_1 = 'C:\\this\\path'; so that the backslashes are escaped.
If PHP consumes one level of escaping in your setup, you might even need to write that as C:\\\\this\\\\path.
2

You can use:

echo json_encode('C:\this\path');

json_encode can be used as a filter function for some JavaScript code.

Comments

1

Try this:

var db_1 = 'C:\\this\\path';

For more info: http://www.w3schools.com/js/js_special_characters.asp

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.