Based on some user input fields on a webpage, a string primitive is created that contains some C-style escape sequences. E.G. n t etc.
What is the proper, safe, way of decoding such a string? In most other languages that I’ve used for text processing the string format function can be used for this task; not just replacing magic variables. While it would also be nice if I could pass a map/dictionary/key-value object to the format specification and have it replace those too, it’s possible to work backwards with .replace and manually replace the values.
I’d rather not also re-invent the wheel for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences and ideally all the other supported string Character Escapes could also be decoded https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape
"use strict";
// oversimplified JS function example
function someButtonClicked() {
var userInput = document.getElementsByName("TextBox")[0].value;
var parsed = "";
// userInput contains: ntLine Two, with a tabnLine Three
// userInput contains: "\n\tLine Two, with a tab\nLine Three"
// I want to do the equivalent of this C style code
// char parsed[strlen(userInput)] ; snprintf(parsed, strlen(userInput), userInput)
// NOW parsed = "ntLine Two, with a tabnLine Three"
// Note the previously escaped characters decoded to real characters.
// parsed must be set within the function context, not global context...
// After much searching and trial and error, all I've found is eval :(
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
eval("parsed = `" + userInput + "`")
}
Surely, there has to be a better way than this? However my efforts to use a search engine are greatly hampered by the poorly named ‘unescape’ (Really decodeURIComponent) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape