获取所有4个字母的单词Regex

时间:2016-04-17 08:44:20

标签: javascript regex

要获得由我编写以下代码所划分的所有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;
&#13;
&#13;

但是,我无法在p标签的开头或结尾处获得4个字母的单词,即This&amp;在这种情况下char

另外标记/跨度&gt;正在被选中。 如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

试试这个:

&#13;
&#13;
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;
&#13;
&#13;