我有这个字符串,我想将TEXT1,TEXT2等提取到数组m。
我尝试使用正则表达式,但它没有用。
var regex = /item\b[^>]*>(.*?)<button/g;
var string = '<li id="reminder-1440746981190" class="new-item">TEXT1
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>
<li id="reminder-1440746983703" class="new-item">TEXT2
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>';
var m;
while ((m = regex.exec(string)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
}
alert(m[0]);
有什么想法吗?
答案 0 :(得分:3)
您可以尝试这样:
var str = $('li').contents().filter(function(){
return this.nodeType === 3;
}).text();
console.log(str);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="reminder-1440746981190" class="new-item">TEXT1
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>
<li id="reminder-1440746983703" class="new-item">TEXT2
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>
&#13;
答案 1 :(得分:1)
以下是基于@ Rahul的答案的一段代码,它返回一组修剪过的文本节点:
var arr = [];
$('li').contents().filter(function(){
if (this.nodeValue !== null &&
this.nodeValue.trim().length > 0) {
arr.push(this.nodeValue.trim());
}
});
console.log(arr.filter(Boolean));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="reminder-1440746981190" class="new-item">TEXT1
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>
<li id="reminder-1440746983703" class="new-item">TEXT2
<button class="icon-trash delete-button" contenteditable="false"></button>
<button class="icon-pencil edit-button" contenteditable="false"></button>
</li>
&#13;
结果:["TEXT1", "TEXT2"]