2016-04-24 2 views
-1

名前がデータセット内の名前とまったく同じではないにもかかわらず、ユーザーが名前を入力してコードを機能させるようにしたいとします。例:「Camden」の入力は機能しますが、「camden」の入力は機能せず、エラーが返されます。入力クエリに寛容を許す方法は?

コードを作成するには、たとえば、大文字でない文字や間違った文字を使用できますか?

app.get("/api/borough_by_name", function(req, res){ 
    // set the type of content in the response 
    res.writeHead(200, {'Content-Type': 'application/json'}); 

    // read input parameter from request 
    var name = req.query['name']; 

    // validate input, check if the parameter is valid or not 
    if (name === undefined){ 
     // return error as a JSON string 
     var str = JSON.stringify({"error":"Parameter 'name' is not defined."}); 
     res.end(str); 
    } 

    var borObj = null; 
    // loop over the statesData GeoJSON structure 
    for (i in londonBoroughs.features){ 
     var feat = londonBoroughs.features[i]; 
     if (feat.properties.NAME == name){ 
      borObj = feat; 
      continue; 
     } 
    } 

    if (borObj == null){ 
     // borough not found, return an error as a JSON string 
     var str = JSON.stringify({"error":"NAME '"+name+"' doesn't exist. Please check the spelling."}); 
     res.end(str); 
    }  

    var respJson = {}; 
    respJson["results"] = [ borObj ]; 
    res.end(JSON.stringify(respJson)); 
+0

あなたは「寛大」のためのあなたの基準は正確に何で自分自身のために決定する必要があります。 – Pointy

答えて

1

あなたができる最も簡単な方法は、両方の変数を大文字と比較することです。str.toUpperCase();など

だから、それは任意の文字にマッチします名前に大文字、カムデン、カムデン、

feat.properties.NAME.toUppercase() == name.toUppercase() 
+0

"feat.properties.NAME.toUppercase()== name.toUppercase()は関数ではありません"というエラーが発生しました – Luffydude

+0

Luffydude、関数はtoUpperCase()で、toUppercaseではありません(Cは大文字です)また、toUpperCase()関数を使用するには、プロパティは文字列でなければならず、オブジェクトであってはなりません。 console.log(feat.properties.NAME)を作成し、文字列またはオブジェクトをエコーするかどうかを確認します。 –

+0

サーバは大文字のCで動作しますが、 "var feat"と "for"の間の行を使用しようとしましたが、それでも存在しないというエラーを返します。ラインはどこか別の場所に行くべきですか? – Luffydude

1

あなたはケースの正規化のための文字列の方法toLowerCaseまたはtoUpperCase使用することができます:あなたはexamle https://github.com/gf3/Levenshteinのため、多くの実装を見つけることができますlevenshtien distanceで見ることができ、間違った文字については

> var name = "Camden" 
> name.toLowerCase() === "camden" 
true 

を。

0

唯一の文字が間違っているかどうかを確認するには、次の

あなたはレーベンシュタイン距離アルゴリズムを使用することができます2つの文字列間の距離を計算します。

if (getDistance("camden", "calden") === 1) { … } 

this implementation(最初のもの)。


大文字と小文字を区別チェックせずに2つの文字列を比較するには:

if ("Camden".toLowerCase() === "camden") { … } 
関連する問題