Search code examples
c#escapingapostrophe

Single Quote Escape Character Formatting for JavaScript


I have a question that I feel will be simple to answer: I have the code

   function ApplicantNameMatchedInitialPayment() {
        var applicantName = '<%= ViewData["ApplicantName"] %>';
        var fullName = applicantName.split(' '); 
        if (fullName.length == 2)
        {
            var firstName = fullName[0].toLowerCase();
            var lastName = fullName[1].toLowerCase();
            var nameOnCard = $("#name-on-card").val().toLowerCase();
            if(nameOnCard.includes(firstName) & (nameOnCard.includes(lastName)))
            {
                return true;
            }
        }
        return false;
    }

I am trying to handle a case where my user enters their name with an apostrophe. When the ViewData Object is filled during live execution, the customer's name will show up in the 'applicantName' variable. The problem is that if I enter a name like "De'Leon", a JS error is thrown in the console because of an incorrect escape sequence.. and the string will not be read correctly. I want to take any string that is passed in from my C# Viewdata object and handle the apostrophes dynamically so that no errors are thrown and so that my javascript understands that everything should just be one string. A little help with the string formatting and escape character?


Solution

  • If you want to just escape apostrophes in JavaScript you could try to simply replace them with \’:

    s = s.replace("'", "\'");
    

    It won’t affect your further work with this string so if you write it to the console it will output a result without backslash:

    var s = "De'Leon";
    s = s.replace("'", "\'");
    console.log(s); // > De'Leon