Skip to content

Instantly share code, notes, and snippets.

@RReverser
Last active October 26, 2015 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RReverser/8e79df1b9df28c0dd94a to your computer and use it in GitHub Desktop.
Save RReverser/8e79df1b9df28c0dd94a to your computer and use it in GitHub Desktop.
function *getSymbols(s) {
for (var i = 0; i < s.length - 1; i++) {
if (s.charCodeAt(i) >> 10 === 0x36 && s.charCodeAt(i + 1) >> 10 === 0x37) {
yield s.substr(i, 2);
} else {
yield s.charAt(i);
}
}
yield s.charAt(i);
}
// Just slightly shorter, you know :)
function getSymbols(s) {
var output = [];
for (var i = 0; i < s.length - 1; i++) {
if (s.charCodeAt(i) >> 10 === 0x36 && s.charCodeAt(i + 1) >> 10 === 0x37) {
output.push(s.substr(i, 2));
} else {
output.push(s.charAt(i));
}
}
output.push(s.charAt(i));
return output;
}
function getSymbols(string) {
var i, output = [];
for (i = 0; i < string.length - 1; i++) {
var charCode = string.charCodeAt(i);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
charCode = string.charCodeAt(i + 1);
if (charCode >= 0xDC00 && charCode <= 0xDFFF) {
output.push(string.slice(i, i + 2));
i++;
continue;
}
}
output.push(string.charAt(i));
}
output.push(string.charAt(i));
return output;
}
@mathiasbynens
Copy link

For reference, my old version was:

function getSymbols(string) {
  var length = string.length;
  var index = -1;
  var output = [];
  var character;
  var charCode;
  var second;
  while (++index < length) {
    character = string.charAt(index);
    charCode = character.charCodeAt(0);
    if (charCode >= 0xD800 && charCode <= 0xDBFF) {
      second = string.charAt(index + 1);
      if (second >= '\uDC00' && second <= '\uDFFF') {
        ++index;
        output.push(character + second);
      }
      continue;
    }
    output.push(character);
  }
  return output;
}

I’ve updated https://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols now. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment