Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Soundex in JavaScript
/**
* Soundex in JavaScript
*
* @example
* // returns 'H416'
* soundex('Heilbronn');
*
* @example
* // returns 'L222'
* soundex('Lissajous');
*
* @example
* // returns 'S532'
* soundex('Soundex');
*
* @param {String} string
* @return {String} result
*/
function soundex(string) {
if (!string) return;
string = string.toUpperCase();
var result = [string[0]],
max_length = 4,
current_char,
rules = {
B: 1,
F: 1,
P: 1,
V: 1,
C: 2,
G: 2,
J: 2,
K: 2,
Q: 2,
S: 2,
X: 2,
Z: 2,
D: 3,
T: 3,
L: 4,
M: 5,
N: 5,
R: 6
};
for (var i = 1, len = string.length; i < len && result.length < max_length; i++) {
current_char = rules[string[i]];
if (current_char && string[i] != string[i - 1]) {
result.push(current_char);
}
}
for (var i = 0, len = result.length; i < max_length - len; i++) {
result.push(0);
}
return (result.join(''));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment