0

I am trying to split a string by : and by \n. I am not sure as to why the line of code below does not work.

let contents = response.split("[:\n]");
user3131097
  • 43
  • 2
  • 10
  • 8
    You should use a regex - `response.split(/[:\n]/)` – Wiktor Stribiżew Nov 09 '17 at 22:02
  • I thought the line of code above is a regex. – user3131097 Nov 09 '17 at 22:03
  • Only if you read [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)... – revo Nov 09 '17 at 22:03
  • Note the use of wrapping `//` vs `""` – msanford Nov 09 '17 at 22:04
  • It's just your syntax that's off. Play around with it on this: https://regex101.com/ – Andrew Nov 09 '17 at 22:05
  • Ah, I thought I had to put the expression in quotes. Guess that only applies when splitting on a single character? – user3131097 Nov 09 '17 at 22:05
  • 2
    You can use a string here -- you are just using the wrong one. This works fine for colon AND new line: `response.split(":\n")` – Mark Nov 09 '17 at 22:06
  • @user3131097 No, `""` is how you build a string, `//` is how you build a regex in JavaScript. (Though some functions will try to cast a string parameter to a regex, yeah ok it's not always clear...) – msanford Nov 09 '17 at 22:06
  • 3
    Guys like @WiktorStribiżew who don't even care about the rep and just put the answer in the comments always impress me. – Joseph Cho Nov 09 '17 at 22:06
  • @JosephCho The question is an evident dupe/typo question. It should be removed. – Wiktor Stribiżew Nov 09 '17 at 22:07
  • @user3131097 When you provide a string to `split` it will litterally look for that string and use it as a separator. If you want a regex you should provide a regex using: **1.** regex literal: `.split(/.../)` or **2.** a regex object: `.split(new RegExp("..."))`. – ibrahim mahrir Nov 09 '17 at 22:07
  • This splits on a `:` or a `\n`. `response.split(/[:\n]/) ` If you want `:` AND `\n` you don't need the brackets: `response.split(/:\n/)` – Mark Nov 09 '17 at 22:08
  • Because he knows well about banal question which is gonna be closed. @JosephCho – revo Nov 09 '17 at 22:08

0 Answers0