KnockoutJS show escaped characters in input but save not escaped

1k views Asked by At

Given an input field such as <input data-bind="value: myText"> with a view model self.myText = ko.observable('\t'). How do I get the input to display \t instead of the tab?

The text field is used for deciding what the separator in a file should look like. If the field simply shows a tab, the user might not know that there is already an existing value.

If you type in \t into the text field, it however saves the correct value '\t'. When retrieving this it will display the tab again

I'm aware that it will work when I set the default value to '\ \ t' but I don't want to escape it as I cannot be sure that the user input is escaped/not escaped and this will most likely lead to errors

1

There are 1 answers

0
Matin Kajabadi On BEST ANSWER

You can use JSON.stringify to get the output whatever it contains in string literal form. Then you can remove the outer quotes from the output (you may want to create a computed variable and have myText observable inside your computed function as a dependency and then whenever a user uses any escape characters it does the job.

Example:https://jsfiddle.net/rnhkv840/24/

 str = "\t";
 self.myText = ko.observable(JSON.stringify(str).replace(/\"/g, ""))