Search code examples
javascriptjqueryangularjsregexangular-filters

Regex issues with word-replacing filter in angular


I am using the filter below to convert the string to camel case. In addition to this I do not want a string with alphanumeric characters to be converted to camelcase.

For example:

If the input is "HELLO I AM INDIA1237"

The output has to be "Hello I Am INDIA1237"

my filter is as below:

angular.module('app')
 .filter('titleCase', function() {
return function(input) {
  input = input || '';
  input = input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); //convert to camelcase
  return input.replace(/[A-Za-z0-9 ]/, function(txt){return txt.toUpperCase();}); //retain alphanumeric string in uppercase

};
});

the second condition does not seem to be working. Can anyone please help.


Solution

  • Your regular expressions are not correct.

    \w matches alphanumeric characters, so your first regex should not use that rule. You probably want: /[A-Za-z]+/

    Your second regex has two things wrong. Firstly, it only matches one character. Secondly it it will always match the same things the first one does.

    You want a regex that only matches words that have a digit. So you need something like: /[A-Za-z]+[0-9][A-Za-z]*/. This will match one or more letters, followed by at least one digit, followed by zero or more letters or digits. If these words always end only in digits, then you could simplify it to /[A-Za-z]+[0-9]+/.