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(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;
}
but i should use same function on client side with javascript. is it possible to convert above function to js ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With