Comparing characters within a string: Using brackets notation or charCodeAt()?

I’ve made these function which counts and returns the occurrences of a given character within a string.

function getOccurences (stringToSearch, charToSearch) {
  var ret = 0;
  var codeToSearch = 0;
  var i;
  
  stringToSearch = stringToSearch.toUpperCase();
  codeToSearch = charToSearch.toUpperCase().charCodeAt(0);

  for (i = 0; i < stringToSearch.length; i++) {
    if (stringToSearch[i].charCodeAt(0) === codeToSearch) {
      ret++;
    }
  }
  
  return ret;
}

I use the charCodeAt()-method of String for to get the UTF-code of each character. Then compare these code with the code of the searched character.

One can compare characters directly as well. Internally the computer uses just numbers anyway.

I’ve made this variation of the original function:


function getOccurences2 (stringToSearch, charToSearch) {
  var ret = 0;
  var i;
  
  stringToSearch = stringToSearch.toUpperCase();
  charToSearch = charToSearch[0].toUpperCase();

  for (i = 0; i < stringToSearch.length; i++) {
    if (stringToSearch[i] === charToSearch) {
      ret++;
    }
  }
  
  return ret;
}

They both work:

console.log('Version 1: %s', getOccurences(example, 'm'));
console.log('Version 2: %s', getOccurences2(example, 'm'));

/*
  RESULT:
  
  Version 1: 5
  Version 2: 5
*/

So therefore my question:

Which possibility to access characters should one prefer (and for what reasons)?

  • Comparing characters directly ?

… or …

  • Comparing characters code ?

Is considering that the computer breaks down the characters into numbers anyway the usage of charCodeAt() just unnecessary waste?

1 Like

It depends on if you have unicode characters from the astral planes (resp. surrogate pairs). then your only choice is codePointAt().

see https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/ for more information.

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.