-2

How do I find and extract capitalized words of a string with regex?

I would like to:

  1. extract the capitalized words of a string, as an array
  2. extract the last capitalized word of a string, as a substring:

Both with one regex

If I have this:

var str="This is a STRING of WORDS to search";

I would like to get this 1:

allCapWords // = ["STRING", "WORDS"]

and 2:

lastCapWord // = "WORDS"
Simon Rigét
  • 2,757
  • 5
  • 30
  • 33
  • 3
    There are two sections with "I would like to". I think you wanted to replace the last one with the section "I tried this.... But got this... ". – Wiktor Stribiżew Jan 26 '16 at 10:10
  • I ask for two variations of a solution: 1. for all words and 2. for just the last one. Have edited question. Thanks. – Simon Rigét Jan 26 '16 at 10:15
  • http://stackoverflow.com/questions/4598315/regex-to-match-only-uppercase-words-with-some-exceptions – BeNdErR Jan 26 '16 at 10:15

3 Answers3

7

To extract the words into an array:

var allCapWords = str.match(/\b[A-Z]+\b/g);
-> ["STRING", "WORDS"]

(Here's a Regex101 test with your string.)

To pull the last word:

var lastCapWord = allCapWords[allCapWords.length - 1];
-> "WORDS"
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
2
 var str="This is a STRING of WORDS to search";
 var regObj =  /\b([A-Z]+)\b/g;  
 allCapWords = str.match(regObj);
amow
  • 2,203
  • 11
  • 19
1

You can try this regexpr /\b[A-Z]+\b/gor \b[A-Z0-9]+\b/g if you are interested in catch numbers inside the string

Ismael Infante
  • 522
  • 4
  • 8