问题
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>')
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?
回答1:
Don't build HTML by concatenating strings. It's not safe (think special characters and XSS).
How about:
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);
});
If you don't want to build DOM elements manually, use one of the mature HTML templating libraries (for example Handlebars).
回答2:
You can use capture group to put the string between 2 \d.
or \d\.
and end of the string with </li>$1<li>
(put the first group between list tag):
s.replace('/^\d\.(.+)(\d\.|$)/gm','/</li>$1<li>/')
来源:https://stackoverflow.com/questions/30267695/matching-only-the-beginning-anchor-of-a-multiline-string