AA Shakil
AA Shakil

Reputation: 556

Unexpected result with Regular Expression in JavaScript

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?

Upvotes: 0

Views: 78

Answers (2)

felixmosh
felixmosh

Reputation: 35493

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.

Upvotes: 3

Geoffrey Wiseman
Geoffrey Wiseman

Reputation: 5637

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.

Upvotes: 0

Related Questions