nodeJS for each new line in a variable, add a hyphen?

时间:2016-10-19 15:51:35

标签: javascript nodes

I have a single string variable that when logged to console looks like the following with line breaks:

index
project.json 
extras

I would like to be able to print it like:

-index
-project.json
-extras

what would be a good way to start on this? I am still in the process of learning JS, so I really have nothing to show for what I've tried, sorry.

I have tried some of the methods(console.log('-' + files_var)), but this does:

that does this:

 - index
  project.json
  extras

1 个答案:

答案 0 :(得分:0)

您可以使用换行符替换所有换行符和使用- .replace()替换所有换行符/...regex.../并将其赋予全局,以便替换所有实例。请记住,第一个字符串没有换行符,所以我们需要手动添加它。

console.log("-" + files_var.replace(/\n\r/g, '\n\r -'))

DEMO