Escaping HTML markup while still calling variable

Twine Version:
Sugarcube 2.37.3

So, I’m having trouble with displaying special characters that seem to format the HML (EXs: ! # $) within a password. I still need it to be a variable because it is an input the player created that an NPC finds and types in.

When I try to simulate the NPC typing it in, it seems to just adds HTML styling than the special character. When I attempt to wrap the password variable in {{{ }}} it displays $Password and not the text associated with the variable.

I’ve seen using certain phrases to force HTML to display certain characters but those were all static creations, not any type of input. Is there possibly an easier way to display these special characters than running a conversion script that I would need to develop?

Here is the test code:

::Password Display
<<set $Password01 = "!abcd234">>
<<set $Password02 = "#abcd124">>

<span id= "DisplayPassword01"> </span>

<span id= "DisplayPassword02"> </span>
<<timed 40ms>>
<<replace "#DisplayPassword01">><<type 1s>>$Password01<</type>><</replace>>
<<next 2s>>
<<replace "#DisplayPassword02">><<type 1s>>{{{$Password02}}}<</type>><</replace>>
<</timed>>

Ok so after looking more into the documentation I found using RegExp.escape() to be what I was looking for.

Updated code if anyone else needs something like this:

<<set $Password01 = "!abcd234">>
<<set $Password02 = "#abcd124">>

<div id= "DisplayPassword01"> </div>

<div id= "DisplayPassword02"> </div>
<<timed 40ms>>
<<replace "#DisplayPassword01">><<type 50ms>><<set _display= RegExp.escape('$Password01')>> _display<</type>><</replace>>
<<next 2s>>
<<replace "#DisplayPassword02">><<type 50ms>><<set _display= RegExp.escape('$Password02')>> _display
<</type>><</replace>>
<</timed>>
2 Likes

Interesting issue!

The problem here is that the <<type>> macro treats its contents as Twine markup (in SugarCube parlance, it wikifies its contents), and therefore sees ! as a heading and # as a list marker.

Your use of RegExp.escape() turns $Password01 into \\$Password01, so that when it is then printed inside <<type>> it turns back into $Password01 after this stage, and then gets replaced the way you were expecting.

You can do the same thing by escaping the characters inside your password strings. So if you have <<set $Password01 = "\\!abcd234">> it will work as expected without the escape.