Search code examples
javascriptreplaceclipboard

How do I insert a tab character into a string in a clipboard-friendly way?


A string in Javascript can contain tab characters. I can see this in my text editor, and I can copy-and-paste it into my browser console and operate with it (e.g, perform Regex searches for it). When I tried to replace something in the string with the tab character, the string rendered the replacement as literal characters (e.g, \t). “No problem,” I thought; “it’s just the way the console renders stuff.” But when I copy-and-paste the return value shown by the console, I copy the literal characters (e.g, \ and t), not the expected tab.

I’ve tried:

"word word".replace(/\s/, " ") //=> "word\tword" (you can’t see it, but the "   " is a tab character copied from VS Code, and no, the console didn’t transform it to four spaces or \t immediately on paste.)

"word word".replace(/\s/, /\t/)   //=> "word\\tword"

"word word".replace(/\s/, "\t")   //=> "word\tword"

"word word".replace(/\s/, "&#9")  //=> "word&#9word"

"word word".replace(/\s/, "	") //=> "word	word"

"word word".replace(/\s/, &#9)    //=> SyntaxError: Unexpected token '&'

"word word".replace(/\s/, /&#9/)  //=> "word/&#9/word"

...but none of them yield a tab character that I can copy and paste between applications.


Solution

  • Use console.log() to log the result to the console, instead of just using the automatic printing of the expression value. This formats it rather than showing the syntax of a string literal.

    console.log("word word".replace(/\s/, "\t"))