c# - 如何使用 JavaScript 将非英文字符转换为英文

标签 c# javascript regex

我有一个 c# 函数,可以将所有非英语字符转换为给定文本的正确字符。像下面这样

public static string convertString(string phrase)
        {
            int maxLength = 100;
            string str = phrase.ToLower();
            int i = str.IndexOfAny( new char[] { 'ş','ç','ö','ğ','ü','ı'});
            //if any non-english charr exists,replace it with proper char
            if (i > -1)
            {
                StringBuilder outPut = new StringBuilder(str);
                outPut.Replace('ö', 'o');
                outPut.Replace('ç', 'c');
                outPut.Replace('ş', 's');
                outPut.Replace('ı', 'i');
                outPut.Replace('ğ', 'g');
                outPut.Replace('ü', 'u');
                str = outPut.ToString();
            }
            // if there are other invalid chars, convert them into blank spaces
            str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
            // convert multiple spaces and hyphens into one space       
            str = Regex.Replace(str, @"[\s-]+", " ").Trim();
            // cut and trim string
            str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim();
            // add hyphens
            str = Regex.Replace(str, @"\s", "-");    
            return str;
        }

但我应该在客户端使用 javascript 使用相同的功能。 是否可以将上述函数转换为 js?

最佳答案

这应该是您要查找的内容 - 查看要测试的演示。

   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

编辑:更新了演示以添加用于测试输入。

关于c# - 如何使用 JavaScript 将非英文字符转换为英文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618434/

相关文章:

c# - 来自过滤器代码的音频点击/弹出

c# - 发生异常时 Visual Studio 和 Process 卡住(我认为)C#

JavaScript 正则表达式查找以 ".js"但不是 "-min.js"结尾的字符串

javascript - 如何检测每个页面的加载情况?

javascript - VSCode : Snippet - Transform characters to another equal length line

java - 如何通过包装类直接访问类成员方法

c# - .Net Standard 1.6 中的 TypeConverter 替代方案

javascript - 如何强制组件重新加载,使用 Angular 7 进行状态更改

python - 与正则表达式相关的CountVectorizer预处理

正则表达式匹配除了