boski
boski

Reputation: 1146

Regex in JS to find first characters of each word and cast to Uppercase

I am looking for regular expression in JavaScript that will help me to return all first characters of each word in Uppercase:

"To do string" => "TDS"

Most important part is to return new string from old.

Upvotes: 1

Views: 142

Answers (2)

zx81
zx81

Reputation: 41848

Easy, with only two functions:

result = subject.replace(/\B[a-z]+\s*/g, "").toUpperCase();

In the demo, look at the substitutions at the bottom. That's the effect of the regex replacement before the toUpperCase()

How it Works

  • \B matches a position that is not a word boundary, in other words, a spot between two letters.
  • [a-z]+ matches as many letters as possible
  • \s* matches optional spaces
  • we replace all this with the empty string
  • we convert to upper case

Upvotes: 3

Lochlan
Lochlan

Reputation: 2796

"To do string".match(/\b(\w)/g).join('').toUpperCase(); will give you the desired result.

Upvotes: 3

Related Questions