Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid to escape a special characters in javascript

My server returns value as support\testing. When I get this value in client it can be escaped as support testing. \t is escaped as tab space.

How do I avoid escaping special characters in JavaScript?

like image 682
raky Avatar asked Jul 09 '13 15:07

raky


People also ask

What can I use instead of escape in JavaScript?

JavaScript escape() The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.

How do I ignore an escape character in a string?

An escape sequence is a set of characters used in string literals that have a special meaning, such as a new line, a new page, or a tab. For example, the escape sequence \n represents a new line character. To ignore an escape sequence in your search, prepend a backslash character to the escape sequence.

Can I escape HTML special chars in JavaScript?

String − We can pass any HTML string as an argument to escape special characters and encode it.


Video Answer


2 Answers

Your server needs to output the string with proper escaping.

In this case, you want a backslash character in the output; backslash is a special character, so that should be escaped.

The escape sequence for a backslash is \\ (ie two backslashes), but you shouldn't need to think about specific escape codes -- if you're outputting JS data, you should be outputting it using proper escaping for the whole string, which generally means you should be using JSON encoding.

Most server languages these days provide JSON encoding as a built-in feature. You haven't specified which language your server is using, but for example if it's written in PHP, you would output your string as json_encode($string) rather than just outputting $string directly. Other languages provide a similar feature. This will protect you not just from broken backslash characters, but also from other errors, such as quote marks or line feeds in your strings, which will also cause errors if you put them into a Javascript code as an unescaped string.

like image 140
Spudley Avatar answered Oct 17 '22 06:10

Spudley


You can use tagged template literals

var str = (s => s.raw)`support\testing`[0]

The anonymous arrow function will serve as tag and s.raw contains the original input

like image 21
Alexander Praetorius Avatar answered Oct 17 '22 05:10

Alexander Praetorius