3

I have var recommend = 'I recommended Garden Solutions for this Tender Contracting on the basis of\n\n1)Top Scorer for tender\n2)Professional Experience in Building Services\n3)Approved Service Providers';

I want to replace \n with an HTML break and want to display it as below:

I recommended Garden Solutions for this Tender Contracting on the basis of

1)Top Scorer for tender

2)Professional Experience in Building Services

3)Approved Service Providers

I am using JavaScript's replace function

var val = recommend.replace("\n","<br>");

But it's not working.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Navdeep
  • 345
  • 5
  • 6
  • 14
  • You need to insert it into the DOM. – elclanrs Jul 21 '12 at 08:17
  • possible duplicate of [Read line break in a string with JavaScript](http://stackoverflow.com/questions/784313/read-line-break-in-a-string-with-javascript) – JJJ Jul 21 '12 at 08:18
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Álvaro González Apr 26 '17 at 15:40
  • Possible duplicate of [JavaScript replace newline escape sequence with newline](https://stackoverflow.com/questions/24988686/javascript-replace-newline-escape-sequence-with-newline) – kris_IV Sep 15 '19 at 14:14

2 Answers2

7

Use a regular expression (RegExp) literal and the "global" (g) modifier:

var val = recommend.replace(/\n/g, "<br />");

Or use a RegExp directly:

var val = recommend.replace(RegExp("\n","g"), "<br>");
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

By using the RegExp "\n" you just replace the first occurrence. To replace all occurrences you need to add RegExp the modifier g.

So use the following, instead, to replace all occurrences:

var val = recommend.replace( new RegExp( "\n", "g" ),"<br>");

Demo fiddle here.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • yes, I have checked working on demo fiddle. But not working on my file. not replacing '\n' with new line – Navdeep Jul 21 '12 at 08:30
  • 1
    @Navdeep Maybe you should put a fiddle on with _some_ of your code. The method here is correct, so your error must be somewhere else. – Sirko Jul 21 '12 at 08:32