简体   繁体   English

如何在Typescript中小写字符串?

[英]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;
                 });

Just use the:只需使用:

.toLowerCase()

method.方法。

In your case:在你的情况下:

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

Use Javascript's .toLowerCase().使用 Javascript 的 .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;
             });

如果您在angular 2中使用jQuery,请使用toString函数

$('#search').val().toString().toLowerCase()

You can use new string case operators which are available in TypeScript 4.1.0您可以使用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有关更多信息,请参阅此 PR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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