views:

84

answers:

3

Hello all,

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

+6  A: 

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';
David Dorward
I have tried using replace '\' with '\\' but that didn't work.
Abs
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.
David Dorward
Ah I see, I'll do a str_replace with PHP then. Thanks!
Abs
@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.
T.J. Crowder
If PHP consumes one level of escaping in your setup, you might even need to write that as `C:\\\\this\\\\path`.
ndim
A: 

Try this:

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

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

Kasturi
A: 

You can use:

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

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

Ionuț G. Stan