0

I am continually bumping into apostrophe (single-quote) and quotation mark (double-quote) errors in variable JS strings.

This works easily enough

<button onclick="alert('Hi');">Say Hi</button>

Likewise, if a single-quote exists in a literal string, escaping it works.

<button onclick="alert('Sagan\'s Razor');">Aliens Exist</button>

However, when a variable string is used, if the string contains a single-quote it breaks the code.

<button onclick="alert('[@variableSting]');">Say What?</button>

Obviously, I could swap the double-quotes and single-quotes, but that just means the error will move from single-quotes to double-quotes.

Using a function with some encoding seems like it would work, but a single-quote would break the example below before it can even be encoded.

<button id="sandbox-button">More Complicated</button>
<script>
   function customAlert(bEle, aStr) {
     const btn = document.querySelector(bEle);
     btn.onclick = function() {
        alert(decodeURI(aStr));
     }
   }
   customAlert('#sandbox-button', encodeURI('[@variableString]'));
</script>

If [@variableSting], for example, equals I'm trying to keep it simple the code would see

encodeURI('I'm trying to keep it simple')

... which would break.

Can anybody think of a simple and dynamic solution? Cheers

LWSChad
  • 331
  • 3
  • 14
  • If value inside `variableString` is already a string, then you will not require to add any quotes around it, try `onclick="alert([@variableSting]);"`. Never seen the interpolation syntax that u have used. but if you were using Angular then `(click)="alert(variableString)"`. – Nav Kumar V Aug 28 '20 at 19:46
  • Thanks for the comment. [@xyz] is from the Caspio.com Database-as-a-Service platform. It is a literal string that is generated on form-load based on a database record value... not a JavaScript variable of string type. So this unfortunately doesn't work. – LWSChad Sep 01 '20 at 19:36

0 Answers0