How to Convert Non-English Characters to English Using JavaScript

前端 未结 4 1237
野性不改
野性不改 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:25

    This should be what you are looking for - check the demo to test.

       function convertString(phrase)
    {
        var maxLength = 100;
    
        var returnString = phrase.toLowerCase();
        //Convert Characters
        returnString = returnString.replace(/ö/g, 'o');
        returnString = returnString.replace(/ç/g, 'c');
        returnString = returnString.replace(/ş/g, 's');
        returnString = returnString.replace(/ı/g, 'i');
        returnString = returnString.replace(/ğ/g, 'g');
        returnString = returnString.replace(/ü/g, 'u');  
    
        // if there are other invalid chars, convert them into blank spaces
        returnString = returnString.replace(/[^a-z0-9\s-]/g, "");
        // convert multiple spaces and hyphens into one space       
        returnString = returnString.replace(/[\s-]+/g, " ");
        // trims current string
        returnString = returnString.replace(/^\s+|\s+$/g,"");
        // cuts string (if too long)
        if(returnString.length > maxLength)
        returnString = returnString.substring(0,maxLength);
        // add hyphens
        returnString = returnString.replace(/\s/g, "-");  
    
        alert(returnString);
    }
    

    Current Demo

    Edit: Updated the demo to add for testing of input.

提交回复
热议问题