JavaScript soundex
Calculate the soundex key of a string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 | function soundex (str) { // Calculate the soundex key of a string // // version: 1001.2911 // discuss at: http://phpjs.org/functions/soundex // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + tweaked by: Jack // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: soundex('Kevin'); // * returns 1: 'K150' // * example 2: soundex('Ellery'); // * returns 2: 'E460' // * example 3: soundex('Euler'); // * returns 3: 'E460' var s = ''; var i, j, l, p = isNaN(p) ? 4 : p > 10 ? 10 : p < 4 ? 4 : p; var m = { BFPV: 1, CGJKQSXZ: 2, DT: 3, L: 4, MN: 5, R: 6 }; var r = (s = (str+'').toUpperCase().replace(/[^A-Z]/g, '').split('')).splice(0, 1); var sl = 0; sl = s.length; for (i = -1, l = sl; ++i < l;) { for (j in m) { if (j.indexOf(s[i]) + 1 && r[r.length-1] != m[j] && r.push(m[j])) { break; } } } return r.length > p && (r.length = p), r.join('') + (new Array(p - r.length + 1)).join('0');} |
Examples
» Example 1
Running
1 | soundex('Kevin'); |
Should return
1 | 'K150' |
» Example 2
Running
1 | soundex('Ellery'); |
Should return
1 | 'E460' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have soundex goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>