20

I am comparing two strings and I want to lower case a string before comparing. How can I do this? This is my code:

 this.products = response.responseData.sort(function(a,b){

                     if(a.product.productName < b.product.productName){
                         return -1;
                     }
                     if(a.product.productName > b.product.productName){
                         return 1;
                     }
                     return 0;
                 });
1

4 Answers 4

44

Just use the:

.toLowerCase()

method.

In your case:

if(a.product.productName.toLowerCase() < b.product.productName.toLowerCase()){
                         return -1;
                     }

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

Comments

2

Use Javascript's .toLowerCase().

this.products = response.responseData.sort(function(a,b){

                 if(a.product.productName.toLowerCase() < b.product.productName.toLowerCase()){
                     return -1;
                 }
                 if(a.product.productName.toLowerCase() > b.product.productName.toLowerCase()){
                     return 1;
                 }
                 return 0;
             });

Comments

2

You can use new string case operators which are available in TypeScript 4.1.0

Please see example:

type LowerCase<T extends string> = `${lowercase T}`;
const lower = <T extends string>(str: T) => str.toLowerCase() as LowerCase<T>;
const result = lower('UP'); // 'up'

For more information see this PR

Comments

0

The answer is toLowerCase(). In this, for numbers, special characters will not be converted to lowercase, it is as it is.

Comments

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.