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.

4

2 Answers 2

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>");
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

yes, I have checked working on demo fiddle. But not working on my file. not replacing '\n' with new line
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.