Skip to content

Instantly share code, notes, and snippets.

@rfprod
Created June 7, 2017 20:52
Show Gist options
  • Save rfprod/5bb93bf945dd620efe5d1219d6e72eed to your computer and use it in GitHub Desktop.
Save rfprod/5bb93bf945dd620efe5d1219d6e72eed to your computer and use it in GitHub Desktop.
American Soundex
function americanSoundex(names) {
const nArr = names.split(' ');
let o = '';
for (let n = 0, max = nArr.length; n < max; n++) {
let name = nArr[n];
const first = name[0];
let output = first + name.slice(1).replace(/(h|w)/ig, '');
let regX = [/(b|f|p|v)/ig, /(c|g|j|k|q|s|x|z)/ig, /(d|t)/ig, /l/ig, /(m|n)/ig, /r/ig];
for (let i = 0, max = regX.length; i < max; i++) {
output = output.replace(regX[i], i + 1);
}
output = output.replace(/(\d)\1+/g, '$1');
output = output[0] + output.slice(1).replace(/(a|e|i|o|u|y)/ig, '');
if (/^\d.*/.test(output)) { output = first + output.slice(1); }
if (!output.match(/\d/g)) {
output = output[0].toUpperCase() + '000';
} else {
let matches = output.match(/\d/g);
if (matches.length < 3) { output += '000'; }
matches = output.match(/\d/g);
output = output[0].toUpperCase();
for (let i = 0; i < 3; i++) {
output += matches[i][0];
}
}
o += output + ' ';
}
return o.trim();
}
// TEST
americanSoundex("Sarah Connor"); // "S600 C560"

American Soundex

Soundex description

American Soundex description

Rules

  1. Save the first letter. Remove all occurrences of h and w except first letter.

  2. Replace all consonants (include the first letter) with digits as follows:

    2.1. b, f, p, v = 1

    2.2. c, g, j, k, q, s, x, z = 2

    2.3. d, t = 3

    2.4. l = 4

    2.5. m, n = 5

    2.6. r = 6

  3. Replace all adjacent same digits with one digit.

  4. Remove all occurrences of a, e, i, o, u, y except first letter.

  5. If first symbol is a digit replace it with letter saved on step 1.

  6. Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it

A script by V.

License.

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