atul
atul

Reputation: 562

replace in javascript with case conversion

I want to make the first character of every word in a string to uppercase. i am referring to this article Replacement Text Case Conversion.

when i am running the regular expression ([a-zA-Z])([a-zA-Z](\s)) with the replacement text as \u$1\l$2 in my editor (sublime text) it works fine.

However, when i am trying to do the same in javascript using replace method as below, its giving syntax errors and hence fails.

var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var rep = "\\u$1\\l$2";  // here it is giving error
var result = input.replace(regex,rep);

How to resolve this?

I know this problem can be solved using charAt() and toUppercase() method. but I want to do it using regex with replace. :)

Upvotes: 1

Views: 648

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626774

JS regex engine does not support lower- and uppercasing operators \u and \l in the replacement patterns. Use a callback inside String#replace:

var input = "aZ";
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var result = input.replace(regex, function($0,$1,$2,$3) {
  return $1.toUpperCase() + $2.toLowerCase(); 
});
console.log(result);

Note that you can reduce your pattern to /([a-z])([a-z]*\s*)/gi.

Upvotes: 4

Related Questions