How to Convert Non-English Characters to English Using JavaScript

前端 未结 4 1268
野性不改
野性不改 2021-01-19 10:52

I have a c# function which converts all non-english characters to proper characters for a given text. like as follows

public static string convertString(stri         


        
4条回答
  •  难免孤独
    2021-01-19 11:18

    function convertString(phrase)
    {
     var maxLength = 100;
     var str = phrase.toLowerCase();
     var charMap = {
      'ö': 'o',
      'ç': 'c',
      'ş': 's',
      'ı': 'i',
      'ğ': 'g',
      'ü': 'u'
     };
    
     var rx = /(ö|ç|ş|ı|ğ|ü)/g;
    
     // if any non-english charr exists,replace it with proper char
     if (rx.test(str)) {
      str = str.replace(rx, function(m, key, index) {
       return charMap[key];
      });
     }
    
     // if there are other invalid chars, convert them into blank spaces
     str = str.replace(/[^a-z\d\s-]/gi, "");
     // convert multiple spaces and hyphens into one space       
     str = str.replace(/[\s-]+/g, " ");
     // trim string
     str.replace(/^\s+|\s+$/g, "");
     // cut string
     str = str.substring(0, str.length <= maxLength ? str.length : maxLength);
     // add hyphens
     str = str.replace(/\s/g, "-"); 
    
     return str;
    }
    

提交回复
热议问题