3

My function parses through text, grabs parts and generates text only email format. But it also needs to generate html format.

The brain-dead way would be to use if ... else ... and add additional html tags around each paragraph or element. But it will violate DRY (don't repeat yourself) rule.

Is there an elegant way to solve this problem?

Zack Macomber
  • 6,682
  • 14
  • 57
  • 104
Duk
  • 125
  • 1
  • 12

2 Answers2

2

As @Pointy said, you should look into templates. jQuery templates, while in beta, are good enough - although there are lots of alternatives for good javascript templates.

In your case, you would do something like:

$.template("textTemplate", "Hi ${name}!\n\nWelcome as a member!");
$.template("htmlTemplate", "<h1>Hi ${name}!</h1><p>Welcome as a member!</p>");

And then use them like this:

var emailText = $.tmpl("textTemplate", data);

// Show the html
$.tmpl("htmlTemplate", data).appendTo("#container");
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
0

You could use a series of regular expressions to fill in html tags. But be warned that there are lots of warnings out there to not use RegEx for parsing html: RegEx match open tags except XHTML self-contained tags

I would implement the Regular expressions like so:

textVAR=YourTextInput;
htmlVAR=textVAR.replace(Reg Ex, "New html tags");// run through a series of RegEx
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");// fill in html tags where needed
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");// be sure to add "/g" to your RegEx to make it global
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");
alert(htmlVAR);

More resources: Finding URLs is difficult: http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html

Consider using PHP - here is a good resource for finding line breaks: http://us2.php.net/nl2br

Community
  • 1
  • 1
iammatthew2
  • 639
  • 2
  • 7
  • 20