2

For a paragraph like this

<p> This is an exaMPLe </p>

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

elm
  • 20,117
  • 14
  • 67
  • 113
  • @Hacketo quite new to Javascript, checking http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript and http://www.the-art-of-web.com/javascript/search-highlight/ – elm Jun 12 '15 at 07:51
  • 1
    @Hacketo need at least some startup ideas, hence the question; thanks for asking :) – elm Jun 12 '15 at 07:53
  • iter all letters, test if letter.[toLowerCase](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) === letter, then wrap it around a span – Hacketo Jun 12 '15 at 07:54

1 Answers1

6

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;
}
alesc
  • 2,776
  • 3
  • 27
  • 45
  • 1
    Just for completion: If you want to highlight by giving a background color without spaces being skipped, then you have to change the regex to this `/([a-z, \s]+)/g`. But if you want to exclude spaces, the solution is absolutely correct :) – Markai Jun 12 '15 at 08:07
  • 1
    Your regex also matches commas. And you have space defined twice - once as a space, and once as `\s`, which matches any white space character. If you wanted to only add spaces, then `/([a-z ]+)/g` is the way to go. – alesc Jun 12 '15 at 08:13
  • Woops, yes you are right, didn't know that, thanks :) – Markai Jun 12 '15 at 08:15