3

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.

2
  • I think, you want to capitalize dictionary words, since INDIA1237 remains same. This is very difficult, need to reference each word in some dictionary for capitalizing. Commented Dec 16, 2015 at 6:43
  • is there a possible regular expression that can be used to exclude the camelcase filter on the string containing alphanumeric characters? Commented Dec 16, 2015 at 6:46

1 Answer 1

1

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]+/.

Sign up to request clarification or add additional context in comments.

1 Comment

input = input.replace(/[A-Za-z]*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); //convert to camelcase return input.replace(/[A-Za-z]+[0-9][A-Za-z]*/g, function(txt){return txt.toUpperCase();}); //retain alphanumeric string in uppercase

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.