0

Assuming that there is an input field named fieldDelimiter, and user input "\\t", i should translate '\\t' to '\t'. ('\\n' to '\n', '\\u0001' to '\u0001' .etc). Is there a common function to do this?

Phil
  • 157,677
  • 23
  • 242
  • 245
linmu
  • 45
  • 5
  • Why wouldn't replace work, especially since the input value is going to be a string anyway? – Todd Mar 30 '20 at 04:08
  • why not like this: `const newStr = "\\t\\nFoo bar baz \\u0001".replace(/(\\.+)\b/gi, '\$1')` – Todd Mar 30 '20 at 04:23
  • 1
    @Todd "\\t\\nFoo bar baz \\u0001".replace(/(\\.+)\b/gi, '\$1') === "\\t\\nFoo bar baz \\u0001", not wanted. – linmu Mar 30 '20 at 06:23
  • you're right... I was forgetting a crucial detail: I was escaping my own capturing group... lol. "\\t\\nFoo bar baz \\u0001".replace(/(\\\\.+)\b/gi, '\$1') – Todd Mar 30 '20 at 21:09

1 Answers1

1

You can use JavaScript's replace() function to replace \\ to \

https://www.w3schools.com/jsref/jsref_replace.asp

To escape \, you can refer the code below:

<html>
    <body>
        <input type="text" id="inputValue">
        <button onclick="removeSlash()">Remove</button>
        <div id="result">
        </div>
    </body>
    <script>
        function removeSlash(){
            var inputValue = document.getElementById("inputValue");
            var result = document.getElementById("result");
            var removed = inputValue.value.replace("\\\\", "\\");
            result.innerHTML = removed;
        }
    </script>
</html>
  • \ is escape charactor,\t or \u0001 is a single charactor, I can not just replace \\ to \ – linmu Mar 30 '20 at 03:48
  • In your case, if inputValue is '\\t', then removed will still be '\\t', you can never translate '\\t' to '\t' by relace method, just replace '\'. – linmu Mar 30 '20 at 06:32
  • Do you means you have multiple \\t \\n or something? Because based on the code given, it will convert \\t to \t or \\n to \n – Lim Wen Rong Mar 30 '20 at 06:49
  • If in this case, you can refer this answer for replaceall https://stackoverflow.com/questions/1144783/how-can-i-replace-all-occurrences-of-a-string – Lim Wen Rong Mar 30 '20 at 06:50
  • You can try it yourself, then see the result: var value = '\\t'; var removed = value.replace('\\\\', '\\'); – linmu Mar 30 '20 at 07:07
  • '\t' or '\u0001' is just a single character. – linmu Mar 30 '20 at 07:08
  • Or you share source code for us to have better understanding for your condition? – Lim Wen Rong Mar 31 '20 at 08:03