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