Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: A BackSlash as part of the string

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

like image 561
Abs Avatar asked Apr 19 '10 15:04

Abs


People also ask

What is the way to include backslash characters in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do you split a backslash in JavaScript?

If you want to split the string by backslashes and spaces alike, the first step is to split by backslashes, done like this: step2 = str. split("\\"); Note that you have to escape the backslash here.


3 Answers

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';
like image 109
Quentin Avatar answered Sep 18 '22 00:09

Quentin


You can use:

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

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

like image 44
Ionuț G. Stan Avatar answered Sep 20 '22 00:09

Ionuț G. Stan


Try this:

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

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

like image 29
Kasturi Avatar answered Sep 22 '22 00:09

Kasturi