简体   繁体   中英

Not Understanding How to Capitalizing Text in Angular

My friend helped me write a custom filter in AngularJS to help me capitalize one of the values in my object for one of my arrays. But didn't have time to explain to me what he did. Was just wondering if anyone can be kind to help me understand this block of code:

.filter('capitalizetext', function() {
   return function(name) {
name = ( name === undefined || name === null ) ? '' : name;
return name.toString().toLowerCase().replace( /\b([a-z])/g, function(change) {
  return change.toUpperCase();
  });
 };
})

1st part that I don't understand is:

name = ( name === undefined || name === null ) ? '' : name;

Why did he do this?

2nd part I don't understand is:

return name.toString().toLowerCase().replace( /\b([a-z])/g,

I understand that he is changing the string to all lowercase so that he can eventually convert it to capitalize the string but what is this: ( /\\b([az])/g

Not really following what he did there.

Please help!

name = ( name === undefined || name === null ) ? '' : name;

This ensures that name is never null or undefined when using it later.

return name.toString().toLowerCase().replace( /\b([a-z])/g, function(change) {
  return change.toUpperCase();
  });
 };

First change everything to lowercase and replace the first character of EVERY word to the uppercase version. \\b is a boundary matcher :

Eg suppose name = "capItalIze me"

Then

  1. name.toString().toLowerCase(); // => name = "capitalize me"
  2. /\\b([az])/g // means find first letter of every word so will match "c" and "m"
  3. replace( /\\b([az])/g, function(change) {return change.toUpperCase();});} // change 'c' to 'C' and 'm' to 'M';

In the first part:

name = ( name === undefined || name === null ) ? '' : name;

He checks to see if the string is truthy in his "definition", checking if it is undefined or null (as a null/undefined string could raise errors), else if it is, he sets it to an empty string to avoid errors.

The second part he uses a regex expression to modify the string to the filter specification. You can read about regex expression here . I am not well versed in regex, but I think you are on the right track when he converts all characters to lowercase , check the comment made above for the regex explanation, however, if this is the case, he could just do this...

string = string.toLowerCase()
string = string.substr(0, 1).toUpperCase() + string.substr(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM