gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:28:18 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com