'How to lower case a string in Typescript?
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;
});
Solution 1:[1]
Just use the:
.toLowerCase()
method.
In your case:
if(a.product.productName.toLowerCase() < b.product.productName.toLowerCase()){
return -1;
}
Solution 2:[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;
});
Solution 3:[3]
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
Solution 4:[4]
The answer is toLowerCase(). In this, for numbers, special characters will not be converted to lowercase, it is as it is.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sh. Pavel |
| Solution 2 | |
| Solution 3 | captain-yossarian from Ukraine |
| Solution 4 | pavan Jambigi |
