RnD
RnD

Reputation: 1069

Javascript regex find all capital letters

I have a text and I need to replace every capital letter with something else. I got this working code which replaces every first letter and changes it's color to red.

var elements = document.getElementsByClassName("each-word")
  for (var i=0; i<elements.length; i++){
    elements[i].innerHTML = elements[i].innerHTML.replace(/\b([a-z])([a-z]+)?\b/gim, "<span class='first-letter'>$1</span>$2")
  }

Is there a way to make it find only capital letters?

Upvotes: 0

Views: 5379

Answers (3)

Guffa
Guffa

Reputation: 700372

Remove the i switch from the regular expression to make it case-sensitive,
and use capital letters for the first character:

/\b([A-Z])([a-z]+)?\b/gm

Upvotes: 3

KeyNone
KeyNone

Reputation: 9150

If I get you right and you want to replace only capital letters, if they are the first letter of a word, then change your regex to to:

/\b([A-Z])([a-z]+)?\b/gm

I removed the i flag to make it case sensitive and changed the first capturing group to only accept capital letters.

Upvotes: 2

NaCl
NaCl

Reputation: 2723

var elements = //string
for(i in elements){
    if(i >= 'A' && i <= 'Z')
        //something else
}

If we would say, that the elements are just strings, what in fact isn't, but I think this should give you the right idea.

Upvotes: 1

Related Questions