为了让所有 4 个字母的单词都由 any 分隔,我编写了以下代码:
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>');
}
p {
background-color: #eee;
}
.red {
color: red;
}
<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>
但是,在这种情况下,我无法获得 p 标记开头或结尾的 4 个字母单词,即 This
和 char
。
标记/span> 也被选中。 如何解决这个问题?
最佳答案
试试这个:
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>');
}
p {
background-color: #eee;
}
.red {
color: red;
}
<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>
关于javascript - 获取所有 4 个字母的单词正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674424/