Skip to content Skip to sidebar Skip to footer

In Javascript How Can I Get A Value Indicating A Character's General Category Like Java Character.gettype?

input char:a (unicode:97) output type:2 input char:Space (unicode:32) output type:12 in java i can use code: 'int type = Character.getType(unicode)' Character.getType Api

Solution 1:

Well, there's the nodeType property which will tell you if it is a text node or an HTML element, for example. As far as obtaining the unicode category, I don't believe there is a native function for that. You can try this plugin which will offer unicode support for regex:

http://xregexp.com/plugins/

http://www.javascriptkit.com/domref/nodetype.shtml

Solution 2:

There is a regexp plugin which supports Unicode categories: http://xregexp.com/plugins/.

Using that, you could create a function that checks for each category like:

var types = [
    'Ll', 'Lu', 'Lt', 'Lm', 'Lo', 'Mn', 'Mc', 'Me', 'Nd', 'Nl',
    'No', 'Pd', 'Ps', 'Pe', 'Pi', 'Pf', 'Pc', 'Po', 'Sm', 'Sc',
    'Sk', 'So', 'Zs', 'Zl', 'Zp', 'Cc', 'Cf', 'Co', 'Cs', 'Cn'
];

function getType(char) {
    varchar = (char + "").charAt(0);
    for(var i = 0; i < types.length; i++) {
        if(XRegExp("\\p{" + types[i] + "}").test(char)) {
            return types[i];
        }
    }
}

alert(getType(" ")); // alerts Zs, because " " is a space separator character

http://jsfiddle.net/pimvdb/mYfCZ/1/

Post a Comment for "In Javascript How Can I Get A Value Indicating A Character's General Category Like Java Character.gettype?"