仅匹配多行字符串的开始锚点 [英] Matching only the beginning anchor of a multiline string

查看:104
本文介绍了仅匹配多行字符串的开始锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var s = "1. TLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \

2.  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse \

3. whatever..."

s.replace('/^\d\.\s+/gm','</li><li>')

我正在尝试将从MS Word复制的列表结构转换为HTML列表.我知道^可以匹配字符串的开始"锚,他的正则表达式/^\d\.\s+/gm将匹配每个新行.但是我需要区分第一行,这是唯一的整个字符串的开始"锚,也就是用<ol><li>替换/^\d\.\s+/的第一个匹配项,有什么通用的方法吗?

I'm trying to convert a list structure copied from MS word to HTML list. I know ^ can match the 'start of string' anchor, he regex /^\d\.\s+/gm will match every new line. But I need to distinguish the very first new line, which is the unique "start of whole string" anchor, a.k.a replace the first matching of /^\d\.\s+/ with <ol><li>, is there any general way to do this?

推荐答案

不要通过串联字符串来构建HTML.这是不安全的(请考虑特殊字符和XSS).

Don't build HTML by concatenating strings. It's not safe (think special characters and XSS).

怎么样:

var s = "1. TLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \n\
\n\
2.  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse \n\
\n\
3. whatever..."

var ul = document.createElement("UL");

s.replace(/^\s*$\n/gm, "").split(/\n/g).map(function (txt) {
    var li = document.createElement("LI");
    li.textContent = txt.replace(/^\s+|\s+$/g, "");
    return li;
}).forEach(function (li) {
    ul.appendChild(li);
});

如果您不想手动构建DOM元素,请使用成熟的HTML模板库之一(例如Handlebars).

If you don't want to build DOM elements manually, use one of the mature HTML templating libraries (for example Handlebars).

这篇关于仅匹配多行字符串的开始锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆