Ada*_*ght 3 javascript c# regex
我有一个ac#函数,它将所有非英文字符转换为给定文本的正确字符.如下
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;
}
Run Code Online (Sandbox Code Playgroud)
但我应该使用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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:更新了要添加的演示以测试输入.
| 归档时间: |
|
| 查看次数: |
8483 次 |
| 最近记录: |