I have an application which generates a random string on the server-side. This string is rendered on page load. I'm able to access the string with JavaScript by selecting it from the DOM element it's contained in.
Assuming the string is in a variable, str
, for example:
let str = 'rds$$$IgObk';
I have a template in another part of the page which contains placeholders (e.g. {{code}}
). This is accessible in the variable template
, e.g.
let template = 'The code is {{code}} ... ';
What I want to do is replace my placeholder {{code}}
with the value of str
. So the expected output would be:
The code is rds$$$IgObk
When I do the following:
template = template.replace("{{code}}", str);
console.log(template)
The output is:
The code is rds$$IgObk ...
Note that this is missing one of the $
characters (there are 3 in the original str
and there are only 2 in the output).
I understand that certain characters have reserved meanings and this is why it removes one of them when using replace()
.
The character set I have to generate codes consists of:
- A-Z (both uppercase and lowercase)
- Any of these characters
!
,@
,#
, and$
Any of these characters can be used in str
and there is no limit on the number of times any one character can appear, or the order in which they appear. The length of the generated str
is always the same.
All I want to do is use str
literally. For example if it contains any special characters then I just want to put those into {{code}}
. I've reviewed javascript replace() not replacing text containing literal \r\n strings but don't think this answers my particular question.
For background information: Previously I was doing the string replacement server side using PHP's str_replace(). This does exactly what I want because it replaces the string as-is.
Is there a solution to this in JavaScript that doesn't involve using regular expressions, i.e. a way to specify "use this string as-is"?