使用正则表达式创建HTML标记

时间:2011-08-08 22:16:59

标签: javascript regex replace

我正在寻找能够转向的JavaScript功能:

- point one
- point two
- point three

进入HTML:

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

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

假设您的输入是一个字符串(例如"- point one\n- point two...")并且您希望输出为字符串:

function convertListItemsToLiTags(s) {
  return (""+s).replace(/^-\s*(.*?)\s*$/gm, function(s, m1) {
    return "<li>" + m1 + "</li>";
  });
}

答案 1 :(得分:1)

您可以通过删除插入适当标记的不需要的位来将其转换为HTML字符串:

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>');