2017-02-09 59 views
0

你好,我正在努力解決我所遇到的問題:Angular 2 Accent Folding

我有一個自動完成的輸入字段。我想爲它重音。

E.g.

當我與術語mun搜索這兩個詞應該顯示Dortmund & München

我目前擁有的是,如果我與術語mün它列出Dortmund搜索。但是,並非München

accentMap = { 
    'ü': 'u', 
    'Ü': 'u', 
    'ä': 'a', 
    'Ä': 'a', 
    'ö': 'o', 
    'Ö': 'o' 
}; 

let str = ''; 
for(let i = 0; i < input.length; i++) { 
    str += this.accentMap[input.charAt(i)] || input.charAt(i); 
} 

我然後做與str調用返回像DortmundMünchen這些條目的API。

+0

你正在使用什麼樣的'typeahead'?它是否由任何lib提供? – developer033

+0

ng2 bootstrap typeahead – bendajo

+0

我讀了他們的文檔,並且發現了'typeaheadLatinize'輸入。在這種情況下不起作用嗎? – developer033

回答

0

這是因爲您的代碼總是將「mün」轉換爲「mun」,因此該字符串在「Dortmund」中找到,但從未在「München」中找到。

爲了解決這個問題,首先包裝在一個可重複使用的功能代碼:

function removeAccents(input: string){ 
    let accentMap = { 
     'ü': 'u', 
     'Ü': 'u', 
     'ä': 'a', 
     'Ä': 'a', 
     'ö': 'o', 
     'Ö': 'o' 
    }; 

    let str = ''; 

    for(let i = 0; i < input.length; i++) { 
     str += this.accentMap[input.charAt(i)] || input.charAt(i); 
    } 

    return str; 
} 

然後當你想比較對單詞的列表中輸入,使用這樣的語句:

if(removeAccents(input) == removeAccents(word)){ 
    // The input matched the word 
}