简体   繁体   中英

Representing @ symbol in javascript string

I'm trying to access the position of the @ symbol and using the following JS...

 <script>

    
    $(document).ready(function () {
    $("#submitButton").click(function (e) {

            var at = $('#email').val().lastIndexOf("@");
         
       });
    });

  </script>

However this produces a Parse Error:

"");" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.

Do I need an escape character here? When I replace the @ with some other character, say a letter. It does not crash. This code works...

            $("#submitButton").click(function (e) {

            var at = $('#email').val().lastIndexOf("w");
           e.preventDefault();

Assuming you are trying to execute the exact snippet above, the error is telling you that your code is not valid. Specifically, you are missing a closing curly brace ( } ) and a closing parenthesis ( ) )

Here is what it should look like:

 $("#submitButton").click(function(e) { var at = $('#email').val().lastIndexOf("@"); console.log('at', at); e.preventDefault(); }); // <-- Closing } and )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="submitButton">Click Me</button> <input id="email" type="text" value="something@something.com" />

As far as the @ symbol goes, you do not need to escape it in this scenario.

EDIT

The error your getting smells a lot like you're using this in an ASP.NET controller. You might just be including your JS wrong. Try including it by doing it this way:

@scripts {
 <script>

    
    $(document).ready(function () {
    $("#submitButton").click(function (e) {

            var at = $('#email').val().lastIndexOf("@");
         
       });
    });

  </script>
}

I found it. The @ symbol needs an escape character...another @ symbol. This works...

var at = $('#email').val().lastIndexOf("@@");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM