dorado dorado - 7 months ago 12
Javascript Question

Get all 4-lettered words Regex

To get all 4 lettered words delimited by any I have written the following code:



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>





However, I am unable to get the 4 letter words at the start or end of the p tag i.e.
This
&
char
in this case.

Also the markup /span> is getting selected.
How can this problem be solved?

Answer

Try this:

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>