5

I just encountered a strange situation. I want to post a code snippet but after submitting the result is different from what I have in the preview. I also tested this in the browser console which shows me the same result as the preview. So after submitting the output is wrong.

This is the code

const tabbedString = `Prefix    Name    Last Name   Email   Phone   Age Role
    Jim Loco    jilo@fox.com        32  Admin
Mrs.    Sara    Foo safoo@fox.com   124389  44  Admin
Mr. John    Deer    jodeer@fox.com      37  Developer`

const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))

console.log(parsedString)

Expected output

[
  [
    "Prefix",
    "Name",
    "Last Name",
    "Email",
    "Phone",
    "Age",
    "Role"
  ],
  [
    "",
    "Jim",
    "Loco",
    "jilo@fox.com",
    "",
    "32",
    "Admin"
  ],
  [
    "Mrs.",
    "Sara",
    "Foo",
    "safoo@fox.com",
    "124389",
    "44",
    "Admin"
  ],
  [
    "Mr.",
    "John",
    "Deer",
    "jodeer@fox.com",
    "",
    "37",
    "Developer"
  ]
]

When I create this as snippet, as already mentioned, in the preview i get this expected result. However, after submitting its different.

const tabbedString = `Prefix    Name    Last Name   Email   Phone   Age Role
    Jim Loco    jilo@fox.com        32  Admin
Mrs.    Sara    Foo safoo@fox.com   124389  44  Admin
Mr. John    Deer    jodeer@fox.com      37  Developer`

const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))

console.log(parsedString)

4
  • I just thought its probably because SO replaces tabs with 4 spaces, when actually posting.
    – The Fool
    Aug 20, 2020 at 9:39
  • Yes, like you say, there is no tab char in there anymore. So it can't split there.
    – Tom
    Aug 20, 2020 at 9:49
  • Related: meta.stackoverflow.com/q/255953/4014959
    – PM 2Ring
    Aug 20, 2020 at 10:04
  • 2
    @The Fool: The TABs are preserved in the source, but rendered as spaces. Aug 20, 2020 at 14:27

1 Answer 1

5

Just use the escape sequence for the tab character in your string.

const tabbedString = `Prefix\tName\tLast Name\tEmail\tPhone\tAge\tRole\n\t\tJim\tLoco\tjilo@fox.com\t\t32\tAdmin\nMrs.\tSara\tFoo\tsafoo@fox.com\t124389\t44\tAdmin\nMr.\tJohn\tDeer\tjodeer@fox.com\t\t37\tDeveloper`

const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))

console.log(parsedString)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .