faid
faid

Reputation: 405

What's the issue with the "\" character in JavaScript?

What's the problem with "\" character in JavaScript?

This script doesn't work:

var theText='<he:/ll/*o?|>'
function clean(txt) {
var chr = [ '\', '/', ':', '*', '?', '<', '>', '|' ];
for(i=0;i<=8;i++){txt=txt.split(chr[i]).join("")}
return txt;}
alert(clean(theText));

It works when I remove the "backslash" from the array:

var theText='<he:/ll/*o?|>'
function clean(txt) {
var chr = [ '/', ':', '*', '?', '<', '>', '|' ];
for(i=0;i<=7;i++){txt=txt.split(chr[i]).join("")}
return txt;}
alert(clean(theText));

It doesn't work when I write var txt='text\';

The mistake may arise from the quotes joined with backslash, like this: \' or '\'

But I need the / character too, what can I do?

Upvotes: 0

Views: 468

Answers (1)

James Allardice
James Allardice

Reputation: 166021

The backslash escapes the closing quote. You need to escape the backslash itself:

var chr = [ '\\', '/', ':', '*', '?', '<', '>', '|' ];
//           ^--- Add another backslash to escape the original one

This behaviour could come in useful if, for example, you wanted to add a single quote character to your array:

var chr = [ ''', '/', ':', '*', '?', '<', '>', '|' ];
//           ^--- This quote closes the first and the 3rd will cause an error

By escaping the single quote, it gets treated as a 'normal' character and won't close the string:

var chr = [ '\'', '/', ':', '*', '?', '<', '>', '|' ];
//           ^--- Escaped quote, no problem

You should be able to see the difference between the previous two examples from the syntax highlighting applied by Stack Overflow.

Upvotes: 5

Related Questions