Use PHP functions in JavaScript

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
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
function soundex (str) {
    // Calculate the soundex key of a string  
    // 
    // version: 1109.2015
    // 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)
    // +   original by: Arnout Kazemier (http://www.3rd-Eden.com)
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl)
    // *     example 1: soundex('Kevin');
    // *     returns 1: 'K150'    // *     example 2: soundex('Ellery');
    // *     returns 2: 'E460'
    // *     example 3: soundex('Euler');
    // *     returns 3: 'E460'
    str = (str + '').toUpperCase();    if (!str) {
        return '';
    }
    var sdx = [0, 0, 0, 0],
        m = {            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
        },
        i = 0,        j, s = 0,
        c, p;
 
    while ((c = str.charAt(i++)) && s < 4) {
        if (j = m[c]) {            if (j !== p) {
                sdx[s++] = p = j;
            }
        } else {
            s += i === 1;            p = 0;
        }
    }
 
    sdx[0] = str.charAt(0);    return sdx.join('');
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
margolan
30 Sep '10 Permalink

q  Nice! Thanks....


Contribute a New function