Home > database >  print value to screen according to condition
print value to screen according to condition

Time:06-03

I am getting the "address" value from the backend. However, the incoming value is all uppercase. I just want the first letters to be uppercase. I achieved this. But I get an error when "address" value does not come.

const upperCaseFirstLetter = (string) => 
`${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;

const lowerCaseAllWordsExceptFirstLetters = (string) =>
 string.replaceAll(/\S*/g, (word) => `${word.slice(0, 1)}${word.slice(1).toLowerCase()}`
);

let address = '';
address = upperCaseFirstLetter(lowerCaseAllWordsExceptFirstLetters(props.policy.assets.address));

html

<div className="policycard__subinfo">
  {props.policy.assets.address ? (t('policy.policy-cards.address')   address) : null}
</div>

The error in the console is as follows; Cannot read properties of undefined (reading 'replaceAll').

CodePudding user response:

There is probably a better way, but any time I run into an error like that I like to just give it a default value:

const lowerCaseAllWordsExceptFirstLetters = (string) => {
    return (string || '').replaceAll(/\S*/g, (word) => `${word.slice(0, 1)}${word.slice(1).toLowerCase()}`
}

so that if string is undefined, it instead is treated as an empty string and you avoid the error.

  • Related