JavaScript backslash (\) in variables is causing an error

前端 未结 6 2039
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 15:19

In Javascript, when I put a backslash in some variables like:

var ttt = \"aa ///\\\\\\\";
var ttt = \"aa ///\\\"; 

Javascript shows an erro

6条回答
  •  渐次进展
    2020-11-22 16:00

    You have to escape each \ to be \\:

    var ttt = "aa ///\\\\\\";
    

    Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

    because you had to show a message to user that user can't give a name which has (\) character.

    I think the scenario is like:

    var user_input_name = document.getElementById('the_name').value;
    

    Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

    If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

    I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

    var ttt = "aa ///\";
    

    Hence, we assume the asker having problem with escaping.

    If you want to simulate, you code must be valid at first place.

    var ttt = "aa ///\\"; // <- This is correct
    // var ttt = "aa ///\"; // <- This is not.
    
    alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
    

    Now, you only need to do is

    var user_input_name = document.getElementById('the_name').value;
    if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
      alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
      do_something_else();
      }
    

    Edit: I used [] to quote text to be shown, so it would be less confused than using "".

提交回复
热议问题