0

This is my String.

 var re = "i have a string";

And this my expression

var str = re.replace(/(^[a-z])/g, function(x){return x.toUpperCase();});

I want that it will make the the first character of any word to Uppercase. But the replacement above return only the first character uppercased. But I have added /g at the last.


Where is my problem?

beaver
  • 523
  • 1
  • 9
  • 20
AA Shakil
  • 538
  • 4
  • 14

2 Answers2

3

You can use the \b to mark a boundary to the expression.

const re = 'i am a string';

console.log(re.replace(/(\b[a-z])/g, (x) => x.toUpperCase()));

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  1. Before the first character in the string, if the first character is a word character.
  2. After the last character in the string, if the last character is a word character.
  3. Between two characters in the string, where one is a word character and the other is not a word character.
AA Shakil
  • 538
  • 4
  • 14
felixmosh
  • 32,615
  • 9
  • 69
  • 88
0

Vlaz' comment looks like the right answer to me -- by putting a "^" at the beginning of your pattern, you've guaranteed that you'll only find the first character -- the others won't match the pattern despite the "/g" because they don't immediately follow the start of the line.

Geoffrey Wiseman
  • 5,459
  • 3
  • 34
  • 52