2011-01-06 5 views
3

나는 주어진 텍스트에 대해 모든 영어 이외의 문자를 적절한 문자로 변환하는 C# 함수를 사용합니다. 다음과 같이JavaScript를 사용하여 영어 이외의 문자를 영어로 변환하는 방법

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로 변환 할 수 있습니까?

그것을 변환 확실히 가능
+0

더 나은 제목이있을 수 있습니다. JavaScript를 사용하여 영어 이외의 문자를 영어로 변환하는 방법 –

+0

예 Chris, 맞습니다. 나는 그것을 바꿨다. –

답변

5

찾고있는 것이어야합니다. 테스트 할 데모를 확인하십시오.

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

편집 : 입력 테스트를 위해 추가 할 수있는 데모를 업데이트했습니다. 이 오래된 질문이지만

+1

안녕하세요, rionmonster, 코드 감사드립니다. 예 예 : [returnString = returnString.reength (return string = returnString.substring (0, returnString.string (0), returnString.string()) 및 [ = 나는 그것이 힌트를 주었다 ... –

+0

나는 "returnString = returnString.substring (0, returnString(); .length <= maxLength? returnString.Length : maxLength) .trim(); " 같은 일을 성취해야하는 것처럼 if 문으로. 테스트 할 샘플 입력이 없으므로 데모를 만들면 혼란 스러울 수 있습니다. 희망이 도움이됩니다. –

+1

trim()은 네이티브 JS 문자열 함수가 아닙니다. – ken

1

...

ToLower는 ->와 toLowerCase => 교체 교체, 길이 => 길이

당신은 IndexOfAny을 코딩해야 할 것,하지만 더 큰 문제가 없다. 그러나 여기에 내 질문 - 왜 클라이언트 쪽을 할 귀찮게? 왜 서버를 다시 호출하고 코드를 모두 한 곳에서 실행하지 않습니까? 나는 이런 것들을 많이한다. 그것은 결합하는 방법을 설명합니다

http://aspalliance.com/1922

, 클라이언트 측, 서버 측 메서드에 다음 링크를 확인하세요.

+0

안녕하세요, Chris, 귀하의 의견과 도움에 감사드립니다. 나의 상사는 콜백 프로세스에서 js를 사용하는 클라이언트 쪽에서는 원하지 않습니다. RegEx 문서를 js에 구현하려고합니다. –

2
function convertString(phrase) 
{ 
var maxLength = 100; 
var str = phrase.toLowerCase(); 
var charMap = { 
    'ö': 'o', 
    'ç': 'c', 
    'ş': 's', 
    'ı': 'i', 
    'ğ': 'g', 
    'ü': 'u' 
}; 

var rx = /(ö|ç|ş|ı|ğ|ü)/g; 

// if any non-english charr exists,replace it with proper char 
if (rx.test(str)) { 
    str = str.replace(rx, function(m, key, index) { 
    return charMap[key]; 
    }); 
} 

// if there are other invalid chars, convert them into blank spaces 
str = str.replace(/[^a-z\d\s-]/gi, ""); 
// convert multiple spaces and hyphens into one space  
str = str.replace(/[\s-]+/g, " "); 
// trim string 
str.replace(/^\s+|\s+$/g, ""); 
// cut string 
str = str.substring(0, str.length <= maxLength ? str.length : maxLength); 
// add hyphens 
str = str.replace(/\s/g, "-"); 

return str; 
} 
+0

안녕하세요, 코드를 보내 주셔서 감사합니다. 하지만 "Microsoft JScript 런타임 오류 : 개체가이 속성 또는 메서드를 지원하지 않습니다."오류가 발생하는 경우 "if (str.test (rx)) {"행. –

+0

죄송합니다. 수정 됨. – ken

0

이 내가 자주 직면 문제입니다. 나는 그것을 해결하는 방법에 대한 자습서를 썼다. 여기에 있습니다 : http://nicoschuele.com/Posts/75.html

첫 번째로, 함수 내의 모든 분음 문자를 처리해야하며, 빌드 한 사전을 사용하여 모든 언어 별 문자를 처리해야합니다. 예를 들어, "à"은 분음 기호이고 "Ø"는 노르웨이어 문자입니다. 내 자습서에서는 .NET을 사용하여이를 구현하지만 원리는 자바 스크립트에서도 동일합니다.

관련 문제