简体   繁体   中英

Creating HTML tags using regex

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!

Assuming your input is a string (eg "- 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>";
  });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM