elm
elm

Reputation: 20415

How to highlight lowercase letters with JavaScript?

For a paragraph like this

<p> This is an exaMPLe </p>

how to highlight the lowercase letters with a different color using Javascript?

Upvotes: 2

Views: 285

Answers (1)

alesc
alesc

Reputation: 2780

This is a quick and dirty solution using regex find/replace.

var p = document.querySelector("p");
var html = p.innerHTML;

html = html.replace(/([a-z]+)/g, "<strong>$1</strong>");

p.innerHTML = html;

First, you get the paragraph, read its inner HTML. Then use regex to find lowercase a-z letters and wrap them with strong HTML tags. You can also use span and apply a CSS class if you wish. After regex find/replace, set back the HTML value.

Working example: http://jsbin.com/vodevutage/1/edit?html,js,console,output

EDIT: If you wish to have a different colour, then change the one line as follows:

html = html.replace(/([a-z]+)/g, "<span class='highlight'>$1</span>");

and also define a CSS class as follows:

.highlight {
    background-color: yellow;
}

Upvotes: 6

Related Questions