-3

I have a single string with spaces. Like "Dmitry Vladimirovich Nikitin". My task is to trim a string and replace all spaces with '\n'.

So, as a result I will get:

Dmitry \n Vladimirovich \n Nikitin \n

var FIO = nameEmployer

console.log(nameEmployer.trim())

FIO = FIO.trim()

FIO = FIO.replace(/ /g, '\n')

As you see, I used '/ /g' expression here to replace all the spaces with '\n'.

But 1 single string (Dmitry Vladi Nikitin) appeared.

enter image description here

What's the problem?

James Skemp
  • 8,018
  • 9
  • 64
  • 107
  • 6
    If that is displayed in an HTML element, the `\n` should be `
    `
    – Asons Jun 26 '18 at 09:54
  • \n is OK in JS. – Dmitry Nikitin Jun 26 '18 at 09:55
  • 1
    \n is ok in an alert. But not in HTML – mplungjan Jun 26 '18 at 09:58
  • its not HTML. its TypeScript – Dmitry Nikitin Jun 26 '18 at 10:06
  • 2
    *"What's the problem?"* -- there are a lot of problems. A picture is worth one thousand words but on [so] it is usually worth a down vote when it is not required to understand the problem. The picture you posted is completely useless. You probably use the string(s) in HTML and no matter how many spaces or newlines you put inside or around them, they are displayed the same way in the browser. HTML doesn't care about your padding spaces either. Use `console.log()` to check the output of your replacement and post that output as text if something doesn't work. – axiac Jun 26 '18 at 10:08
  • @DmitryNikitin You also might want to change your question title, as you actually ask why the text doesn't break line. – Asons Jun 26 '18 at 10:41
  • Possible duplicate of [Line break in html with \`\n\`](https://stackoverflow.com/questions/39325414/line-break-in-html-with-n) – Asons Jun 27 '18 at 09:13
  • One more possible duplicate [How to display a label having text with line breaks?](https://stackoverflow.com/questions/36558282/how-to-display-a-label-having-text-with-line-breaks/36558525#36558525) – Asons Jun 27 '18 at 12:16

2 Answers2

-1

You are trying to find all spaces and replace it with new line character. Regular expression inside replace function is missing \s for space. Below code snippet is working perfectly for me.

var FIO = nameEmployer
console.log(nameEmployer.trim())
FIO = FIO.trim()
FIO = FIO.replace(/\s/g, '\n')
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

nameEmployer = nameEmployer.trim()
nameEmployer = nameEmployer.replace(/ /g, '\n')