dorado
dorado

Reputation: 1525

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?

Upvotes: 1

Views: 87

Answers (1)

timolawl
timolawl

Reputation: 5564

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>

Upvotes: 5

Related Questions