簡體   English   中英

如何在Typescript中小寫字符串?

[英]How to lower case a string in Typescript?

我正在比較兩個字符串,我想在比較之前小寫一個字符串。 我怎樣才能做到這一點? 這是我的代碼:

 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;
                 });

只需使用:

.toLowerCase()

方法。

在你的情況下:

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

使用 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()

您可以使用TypeScript 4.1.0中可用的新字符串大小寫運算符

請看例子:

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

有關更多信息,請參閱此 PR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM