0

I am looking for a javascript function that will be able to turn:

- point one
- point two
- point three

into HTML:

<li>point one</li><li>point two</li><li>point three</li>

Any help would be greatly appreciated!

1
  • Welcome to StackOverflow! Please review the FAQ and consider editing your question a bit. Specifically, please include more details about your problem, especially example code that you've written to try to solve it and an explanation about why it doesn't work for you. Commented Aug 8, 2011 at 22:23

2 Answers 2

1

Assuming your input is a string (e.g. "- point one\n- point two...") and you want your output as a string:

function convertListItemsToLiTags(s) {
  return (""+s).replace(/^-\s*(.*?)\s*$/gm, function(s, m1) {
    return "<li>" + m1 + "</li>";
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is a function of pure beauty! Thank you - it works a treat.
You're welcome! If you think that this answer solves your problem then consider pressing the checkmark next to it to indicate that this is the "right" solution.
1

You can convert it to an HTML string by removing the unwanted bits an inserting appropriate tags:

var s = "- point one\n- point two\n- point three"

// <li>point one<li>point two<li>point three
var html = '<li>' + s.replace(/- /g,'').split('\n').join('<li>');

3 Comments

Change end to .join("</li><li>") + "</li>";
There is no need for LI closing tags, the markup is valid without them, so why put them in?
Interesting. I would have thought HTML wanted a more regular syntax at least for LI elements. In any case, it depends on whether or not the OP wants the closing tags (as in his example).

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.