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?
The backslash escapes the closing quote. You need to escape the backslash itself:
This behaviour could come in useful if, for example, you wanted to add a single quote character to your array:
By escaping the single quote, it gets treated as a ‘normal’ character and won’t close the string:
You should be able to see the difference between the previous two examples from the syntax highlighting applied by Stack Overflow.