Search code examples
javascriptstringescapingquotes

JavaScript string declarations from dynamic data with unescaped quotation marks


I am writing JavaScript templates for a content management system where users fill out text input fields that are passed to my templates.

My problem is the quotation marks in the input fields are not escaped before they are passed to my template, so I have no way of knowing if they will contain single or double quotes, or even both. Whichever way I try to handle the data my code ends up breaking because the quotes terminate the string declaration. I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.

Is there any way to safely handle the data in JavaScript without it breaking a string variable declaration?

Edit: I'm posting code example;

CMS Text Input Field value is: Who'll win our "Big Contest"?

Text Input Field placeholder macro is [%TextInput%]

I'm building an HTML template for this input, using just JS/HTML/CSS

<script>
(function(){
  var textInputStr = "[%TextInput%]";
})();
</script>

This will break the string declaration if the value of TextInput contains a single quote, and vice versa.


Solution

  • This is an awesome question, and one that deserves an answer. Strings in JS don't have a custom delimiter, like in most other modern languages, so you can get really stuck. But one solution is to build a script tag with the placeholder inside it, then find the innerHTML of that tag and grab the string back into a variable. eg

    <script id="parseMe" type="text/template">
    [%TextInput%]
    </script>
    

    then use

    var yourString = document.getElementById("parseMe").innerHTML
    

    Now you can manipulate the string as you please.

    HTH!