要获得由我编写以下代码所划分的所有4个字母单词:
function select() {
var html = document.getElementById('p').innerHTML;
var fourLettered = html.match(/[^a-zA-Z|^$][a-zA-Z]{4}[^a-zA-Z|^$]/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
&#13;
p {
background-color: #eee;
}
.red {
color: red;
}
&#13;
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>
&#13;
但是,我无法在p标签的开头或结尾处获得4个字母的单词,即This
&amp;在这种情况下char
。
另外标记/跨度&gt;正在被选中。 如何解决这个问题?
答案 0 :(得分:5)
试试这个:
function select() {
var html = document.getElementById('p').textContent;
var fourLettered = html.match(/\b[a-zA-Z]{4}\b/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
&#13;
p {
background-color: #eee;
}
.red {
color: red;
}
&#13;
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>
&#13;