Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Comparing characters and accented characters

I'm creating a simple hang man like game. The user can input a "secret sentence" and then the players have to guess it by chosing letters one by one.

Since this game will be used in several languages, I would like to solve all accented character if a player chose the non-accented character. For example:

IL CANE È BELLO.

If the player choses the vowel "e" only the vowels without accent will be solved (the game compares characters with ===). Instead I would like that the game recognizes automatically all chars accented or not (è, é, e...)

I'm about to torture myself writing a function that checks every accented character, but I was wondering if ther might be an easier way.

This is what my funciton look like so far (I just added the è accented vowel)

function isAccentedVowel(chosenChar, currentChar) {
    console.log('The user selected this char: ' + chosenChar)
    console.log('I\'m comparing it to this char: ' + currentChar)
    switch (chosenChar) {
        case 'E':
            if (currentChar === 'È') return true;
    }
}

note: the secret sentence and every character are uppercase

like image 446
devamat Avatar asked Aug 30 '19 04:08

devamat


2 Answers

You'll want to use String.prototype.localeCompare() with sensitivity value of "base". This has the added bonus of comparing case-insensitively (which I assume you'll also want).

If your characters match, localeCompare() returns 0.

Here's an example based on the assumption that you'll want to find the positions of the matching characters (ie, a "hang man" game)

const locale = undefined // set this if it matters, otherwise use default
const options = { sensitivity: 'base' }

const findCharPositions = (str, char) => 
  Array.prototype.reduce.call(str, (indexes, c, i) =>
    (c.localeCompare(char, locale, options) || indexes.push(i), indexes), [])

const str = 'IL CANE È BELLO'
console.log('Find "l":', findCharPositions(str, 'l'))
console.log('Find "e":', findCharPositions(str, 'e'))
like image 148
Phil Avatar answered Nov 17 '22 01:11

Phil


You can use String#normalize to compare the accented characters with their normal counterpart.

To perform comparison, you need to first get/extract normal character from accented character as below.

string.normalize('NFD')

This will return an array containing two items. You can now compare the first item in the array with normal characters.

function isAccented(char, accentedChar) {
  return char === accentedChar.normalize('NFD')[0];
}

console.log(isAccented('E', 'È'));
like image 34
Tushar Avatar answered Nov 17 '22 02:11

Tushar