我正在使用angularjs
应用
我从后端接收数据作为数组。我需要将其转换为HTML列表。 (使用li
)但我该怎么做?
这是我得到的数组string
:
"1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication."
我想将此转换为无序列表,如下所示:
<ul>
<li> Submittals in progress </li> //see the number removed.
<li> Structural works in progress in S2 & S3 </li>
<li> Structural works in progress in N4. </li> //end has the dot
<li> Childrens Mall pedestal and steel fabrication. </li>
</ul>
答案 0 :(得分:4)
您可以使用这个基于前瞻性的正则表达式:
var s = "1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication.";
var r = "<ul>\n" +
s.replace(/\b\d+\.\s+(.+?)\s*(?=\b\d+\. |\s*$)/g, "<li> $1 </li>\n") +
"</ul>\n";
console.log(r);
<强>输出:强>
<ul>
<li> Submittals in progress </li>
<li> Structural works in progress in S2 & S3 </li>
<li> Structural works in progress in N4. </li>
<li> Childrens Mall pedestal and steel fabrication. </li>
</ul>
RegEx分手:
\b\d+ # match 1 or more digits after a word boundary
\. # match one literal dot
\s+ # match 1 or more space
(.+?) # match 1 or more any character and capture it group #1
\s* # match 0 or more spaces
(?=...) # a positive lookahead
(?=\b\d+\. |\s*$) # match must be followed by a word boundary + digits + dot OR
# white spaces + line end
更新:要从原始字符串中获取匹配项的数组,请使用String#match
:
var arr = s.match( /\b\d+\.\s+(.+?)(?=\s*\b\d+\. |\s*$)/g );
这将给出:
["1. Submittals in progress",
"2. Structural works in progress in S2 & S3",
"3. Structural works in progress in N4.",
"4. Childrens Mall pedestal and steel fabrication."]
答案 1 :(得分:1)
您可以从 angular js docs或stack overflow 寻求有关如何使用ng-repeat的帮助
var str = "1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication."; //sample string
var result = str.split(/^\d+\.+\s+|\s\d\.\s/); //just skip text at index zero
//use ng-repeat and print in whatever way you wanted
result = str.split(/(^\d+\.+\s+|\s\d\.\s)/); //if numbers are also required
答案 2 :(得分:0)
做动态anubhava建议的同样的事情。你可以使用list#appendChild
。
创建一个函数,传递你的字符串和要追加的列表项。
var strs = "1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication.".match(
/\b\d+\.\s+(.+?)\s*(?=\b\d+\. |\s*$)/g);
var list = document.getElementById('list');
for (var i in strs) {
var anchor = document.createElement("a");
anchor.href = "#";
anchor.innerText = strs[i];
var elem = document.createElement("li");
elem.appendChild(anchor);
list.appendChild(elem);
}
<ul id = "list">
<li>1</li>
<li>2</li>
</ul>
PS:添加锚点只是为了展示如何改变它的样本。